I have a sender()
function, which sends out UDP packet. At the end of the sender()
it wakes up a receiver thread to wait for the UDP response with a timeout.
Here the sender()
could be called by main thread or by the receiver thread. Receiver thread after receiving a response message or timeout, it may decide to send a new packet. That's why, the sender()
should be able to called from receiver's context too. The pesudo code is as follows:
std::mutex m;
std::conditional_variable reciever_cv;
void sender()
{
request = create_new_packet();
socket.sendBytes( request );
receiver_cv.notify_one();
}
// receiver() gets started as a thread when system is up
void receiver()
{
while(true)
{
std::uniq_lock lock(m);
receiver_cv.wait( lock, [](){ return predicate; }); // predicate could be anything
socket.receiveBytes();
// ... some processing
if( new packet needs to be sent )
{
sender();
}
}
}
My question here is that can a thread notify itself to wakeup in the next loop?
My task is simple. The only complication is there is a function shared by different threads. I hope the number of wakeup is memorized somehow, and the receiver just wakes up to match that number.
So far, all online materials I have browsed give suggestion on issuing notification from a separate thread.
Would counting semaphore a better approach in my case?
wait
when it callsnotify_one
. Hence, it cannot be notified at all. Someone else will be. If you wantwait()
to be woken up bysender()
, you should really include that intopredicate
somehow to have a precise semantics. Otherwise, it all seems very TOCTOU-prone tome.notify
notifieswait
ing threads. You can't be both a notifier and waiting at the same time.receiver()
->sender()
->notify_one()
->...
->receiver()
or something else?