I have the following situation:
There is a thread that reads from a device with a fread call. This call is blocking as long as there is no data send from the device.
In the thread, instead of blocking with fread
, block with select
. When select
returns, check an "am I done" variable. If not done, you can call fread
to get the data.
From the other thread -- that wants to stop the fread thread -- you can set the "am I done" variable and then close the fd so that the fread thread will wake up from select
immediately.
If your context prohibits you from closing the fd (you mention you're reading from a device, but say you had a socket you wanted kept open), you could open a second fd that you write to from the other thread to wake up select
.
As suggested in the comments below, closing the fd to wake up select
may not be portable. You can use the second-fd strategy mentioned above to achieve this more portably.