C++ – How to wake up a thread after receiving 2 packets

How to wake up a thread after receiving 2 packets… here is a solution to the problem.

How to wake up a thread after receiving 2 packets

I’m using libnetfilter_queue for my project. From C application queues are accessible through the Queue File Descriptor. I have 5 queues and 5 threads to process them. What I want to achieve is to wake up the thread when there are exactly 2 packets in the queue. I thought of using the select function and an int array to indicate how many packets are queued in each queue. After opting out with the > 0 code, I check which queue has received the packet and increment the value in the array, and if it’s greater than 2, I wake up a thread. Everything will be fine, but select indicates that the queue has data to read until I call recv and I can’t do that because a separate thread should be processing those packets. Anyone know how to fix this? I know I can set SO_RCVLOWAT but it doesn’t solve my problem because I don’t know the size of these 2 packets.


According to Tobu’s recommendation, epoll is a better choice, and it performs better than select.
However, unless someone reads, most of these polling functions will indicate that there is an event (data available).
If possible, use the following model:
Use epoll/select to observe incoming data wake up worker threads.
Let the worker decide what to do with the data (one packet, two or more) before actually performing the work.

One Reader thread – N worker threads: will use epoll to wait for all incoming data to be read and posted to the queue of the corresponding worker thread.
Once the number of packets reaches the threshold, wake up the worker thread (using semaphore).

Related Problems and Solutions