C ++ What can be used instead of the sleep () function?

I am building a scrobbler and I want my program to wait 10 seconds after changing the song before scrobbling. I use sleep, but I realized that if the song changes in these 10 seconds, the program will send the old song and get a new one. I want, if I change the song, start the code all over again.

I use Music Player Daemon (MPD) and libmpd to get song tags.

Note: the program is under Unix.

+4
source share
2 answers

It greatly depends on how your program works, but in principle, the easiest way would be to save a dream and check if the user changed the song before sending this data (it returns after sleep). Thus, instead of “sleeping better,” the goal would be to “verify that the data you are sending is valid before it is sent.”

Another possibility is to wait on epoll , using either a sleep timeout, or even better on timerfd , and notify the song change using eventfd . The advantage of this is that it is “free” if you still need a reliable notification about the exchange of information and readiness, which you most likely do (obviously, you must have at least one additional GUI thread, or the user will not be able to change songs while you block).

+2
source

Damon's suggestion is good and may be the best overall design. If you are looking for something fast, you can just send a signal to your application when the song changes. This will interrupt the sleep() system call and make it return earlier. Then your application would just have to handle the early return. Depending on your implementation, this may not be acceptable, but it can lead to a quick fix.

+1
source

All Articles