I'm creating application model with three threads based on while(true)
and a blocking function.
- Event thread - waits for user input, blocked by SDL_WaitEvent
- Socked thread - waits for data from server, blocked by blocking socket.
- Render thread - renders data from buffer, not blocked.
I have a problem with rendering thread - i need a blocking function that will, for example, block until some paint event (defined by me and dispatched in one of other two threads) happens.
But I don't know how blocking functions work. I can, of course, create an sleep()
loop, but such loop has fixed FPS takes resources even if nothing happens (I've already elaborated on that topic here). On the oher side, it does not display data immediatelly. This is not good for GUI application.
If you're using C++11, you can use std::condition_variable
and
std::mutex
:
void
waitForEvent()
{
std::unique_lock<std::mutex> lock( myMutex );
while ( ! externalCondition ) {
myConditionVariable.wait( lock );
}
}
To trigger the event:
void
setEvent()
{
std::unique_lock<std::mutex> lock( myMutex );
setExternalCondition();
}
On the other hand, you mention a GUI and a renderer. You
cannot wait on an external condition in the GUI thread. If
you need to be in the GUI thread for rendering, you'll have to
find out how to create a GUI event in your GUI manager, and post
the GUI event.
Looks good. Is there multiplatform version? Or at least, linux
equivalent, so I can write one myself?
Take a look at this thread: WaitForSingleObject and WaitForMultipleObjects equivalent in linux
Stick to pthread_cond_timedwait and use clock_gettime. For example:
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 10; // ten seconds
while (!some_condition && ret == 0)
ret = pthread_cond_timedwait(&cond, &mutex, &ts);