3

I know mutex can be an implementation, however I'm wondering there would be a way to pause/resume another thread as in video-playback. This approach is easier to program when the other running thread is complex.

ABCD
  • 7,914
  • 9
  • 54
  • 90
  • 1
    http://stackoverflow.com/questions/1606400/how-to-sleep-or-pause-a-pthread-in-c-on-linux may help you – Jeegar Patel Oct 18 '11 at 11:48
  • It may be easier to program, but it is harder to get correct. Much harder. Nearly impossible, in fact... – Nemo Oct 18 '11 at 17:41

1 Answers1

1

There's SIGTSTP, a signal for pausing processes, which you could use if you have two processes, but signals have several drawbacks so I wouldn't recommend using them. For a controlled, stable method you'd have to do it yourself using a mutex, where user pausing the playback leads to locking the mutex, and the thread doing the playback tries to lock the mutex . Like this:

static pthread_mutex_t mutex;

/* UI thread */
void g(void)
{
    while(1) {
        get_input();
        if(user_wants_to_pause)
            pthread_mutex_lock(&mutex);
        else if(user_wants_to_resume)
            pthread_mutex_unlock(&mutex);
    }
}

/* rendering thread */
void f(void)
{
    while(1) {
        pthread_mutex_lock(&mutex);
        /* if we get here, the user hasn't paused */
        pthread_mutex_unlock(&mutex);
        render_next_frame();
    }
}

If you need more communication between the two threads you could use the standard IPC mechanisms like pipes - you could then implement pausing and resuming based on that.

Antti
  • 11,944
  • 2
  • 24
  • 29