Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wake up a thread being blocked by select.poll.poll() function from another thread in socket programming in python?

Tags:

python

sockets

I have no way to wake up a thread being blocked by poll.poll() function . Could someone help me ?

like image 664
nguyenngoc101 Avatar asked Aug 21 '12 07:08

nguyenngoc101


2 Answers

The way to handle this is to have an extra file descriptor included in the list of descriptors passed to poll(). For that descriptor wait for a read to be ready. Have any other thread which wants to awaken the thread waiting on poll() write to that extra descriptor. At that point, the thread which called poll() resumes execution, sees that the extra descriptor is that which awakened it, and does whatever.

The normal way to get this extra file descriptor initially is to open an unnamed pipe with pipe(). That way you have two descriptors: the one you hand the read wait in poll() on and the other which you write to to awaken the thread waiting on poll().

like image 83
dnewman Avatar answered Nov 14 '22 21:11

dnewman


There are many legitimate reasons to want to wake up a blocking poll(2) or select(2) before it times out. Any time you need to add or remove a socket from the fd list being polled, you need to break out of the wait. If you rely on the timeout, the timeout has to be short to be responsive, but short timeouts can result in a lot of needless thrashing.

For Linux anyway, you can use eventfd(2) to create a file descriptor to add to your fd list. When you need to break out of the wait, write to the eventfd.

like image 32
KarlU Avatar answered Nov 14 '22 23:11

KarlU