When using multithreading I often run into the following problem:
I’ve got an object, say a network receiver(but could be anything). And a function that gets the data. Now sometimes there simply is no data, and you want to let the thread wait to get it’s data. A blocking call, very much like being used by Berkeley sockets and it’s derived implementations.
The principle is simple:
Well now of course there is other ways of implementing this. But my usual implementation with C++11 is as follows:
Object ACalls the function in object B on a separate thread, that is dedicated to this task.
Object BUses an
std::condition_variableconstruction to block the thread until the data is actually acquired.
Object APlaces the data in a queue, which is read out by the main thread.
Now my actual problem arises on the destruction of
object B, if it has to be destructed before
object A(returning a nullptr, or something similar on the blocking call). I really wouldn’t know how to efficiently wrap up
The main problem is that
object B isn’t aware of the thread, and a thread can only have one handle, which is inside
Now I could cook something up using atomic counters, more
std::condition_variables. But I have a feeling there has to be a more elegant and reliable solution to this problem:).
Note: I’m using C++11, so I’ve used that to illustrate everything. And I’m hoping to solve it using that. Although this of course this is a more of a general concurrency problem.