Custom blocking function in C++

2019-09-03 07:42发布

问题:

I'm creating application model with three threads based on while(true) and a blocking function.

  1. Event thread - waits for user input, blocked by SDL_WaitEvent
  2. Socked thread - waits for data from server, blocked by blocking socket.
  3. 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.

回答1:

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.



回答2:

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);