How to implement a temporary wait for a blocking call?

So the situation is this. I have a C ++ library that does some interprocess communication, with a function wait()that blocks and waits for an incoming message. The difficulty is that I need a wait time that will return with a status value if a message is not received within a certain time.

The most elegant solution is probably to rewrite the library to add latency to its API, but for the sake of this question, I assume that this is not possible. (It actually looks complicated, so I want to know what the other option is.)

Here's how I would do it with a busy wait loop, in pseudocode:

while(message == false && current_time - start_time < timeout)
{
  if (Listener.new_message()) then message = true;
}

I do not want the wait that eats processor cycles. And I also don’t want to just add a call sleep()in a loop to avoid CPU loading, as this means a slower response. I want something that does this with the proper kind of blocks and interrupts. If the best solution includes threads (which seems likely), we already use it boost::thread, so I would rather use that.

I am posting this question because it seems like a situation in which there would be the correct answer of “best practices”, as this is a fairly common pattern. What is the right way to do this?

:. , , , . , " " , , , , , , . , !

, : " " ", , ? , , , , , , ? ? ( ?) , , , .

+3
6

sigaction(2) alarm(2), POSIX. sigaction, , . , ( , , setitimer(2)).

, C , , .

: http://www.gnu.org/s/libc/manual/html_node/Setting-an-Alarm.html

+1

, - (2), , .

+1

, "", (). Boost.Thread condition_variable .

+1

, timed locks: , , . ( ) .

+1

. , ( ). timed-wait . , .

, , API . .

+1

, ?

I believe that you can not do anything to restore purely without cooperation with the called function (or library). Clean means cleaning up all resources belonging to this thread, including memory, other threads, locks, files, file locks, sockets, GPU resources ... It is not clear that you can really kill a runaway thread.

0
source

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


All Articles