How not to intimidate the processor, waiting for any event?

I would like to write code that wakes up (or sleeps up) some kind of event.

I have a piece of code that sleeps until an event occurs, such as when it is alarmed for hours.

Pseudocode:

int main() { TimePoint someTp("3PM"); std::this_thread::sleep_until(someTP); } 

This is my current implementation, but this pig makes up about 10% of my processor power. I think my design is flawed, is there a better solution for this? Thank you very much in advance!

+6
source share
3 answers

The problem is the implementation of std::this_thread:sleep_until(..) , which calls sleep_for(..) , which calls nanosleep() .

(See gnu sources , line 271.)

Pay attention to the following questions in Stackoverflow:

You do not need high resolution nanosleep() . You can write your own open source permissions solution and call sleep() instead of nanosleep().

If you need a sub-second resolution, I recommend the method to call select() rather than nanosleep() . select() designed for very effective blocking for subsecond delays, and the timeout parameter is fairly accurately observed by most operating systems, which is useful for subsecond synchronization, while simultaneously receiving a processor.

You can even create a socket to pass to select() in the error_fds parameter, where the socket can be used as a cross-thread signal when it is passed to close() , and the error state socket becomes.

+8
source

A better solution would be to use an event-driven library like Boost.Asio or libevent rather than sleep for some time.

+3
source

A simple implementation might be to use Semaphore .

Keep the worker thread locked in the semaphore and signal the Semaphore from another thread where the alarm event occurs.

 void* workerThread(void*) { TimePoint someTp("3PM"); sem_Wait(); //Thread remains blocked here } void timercallback() { sem_post(); //Signals worker thread to move ahead } 
+1
source

Source: https://habr.com/ru/post/890164/


All Articles