Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pause/Resume another thread

Tags:

c

pthreads

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.

like image 878
SmallChess Avatar asked Feb 25 '26 06:02

SmallChess


1 Answers

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.

like image 129
Antti Avatar answered Feb 27 '26 19:02

Antti