Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sleep or pause a PThread in c on Linux

Tags:

I am developing an application in which I do multithreading. One of my worker threads displays images on the widget. Another thread plays sound. I want to stop/suspend/pause/sleep the threads on a button click event. It is same as when we click on video player play/pause button. I am developing my application in c++ on linux platform using the pthread library for threading.

Can somebody tell me how I achieve threads pause/suspend?

like image 728
Muhammad Ummar Avatar asked Oct 22 '09 10:10

Muhammad Ummar


People also ask

How do you sleep a thread in Linux?

sleep() causes the calling thread to sleep either until the number of real-time seconds specified in seconds have elapsed or until a signal arrives which is not ignored.

How to sleep a thread in c?

Explanation: When you want to sleep a thread, condition variable can be used. In C under Linux, there is a function pthread_cond_wait() to wait or sleep. On the other hand, there is a function pthread_cond_signal() to wake up sleeping or waiting thread. Threads can wait on a condition variable.

What is Pthread in Linux?

POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time.


2 Answers

You can use a mutex, condition variable, and a shared flag variable to do this. Let's assume these are defined globally:

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int play = 0;

You could structure your playback code like this:

for(;;) { /* Playback loop */
    pthread_mutex_lock(&lock);
    while(!play) { /* We're paused */
        pthread_cond_wait(&cond, &lock); /* Wait for play signal */
    }
    pthread_mutex_unlock(&lock);
    /* Continue playback */
}

Then, to play you can do this:

pthread_mutex_lock(&lock);
play = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);

And to pause:

pthread_mutex_lock(&lock);
play = 0;
pthread_mutex_unlock(&lock);
like image 189
LnxPrgr3 Avatar answered Dec 13 '22 13:12

LnxPrgr3


You have your threads poll for "messages" from the UI at regular interval. In other words, UI in one thread posts action messages to the worker threads e.g. audio/video.

like image 22
jldupont Avatar answered Dec 13 '22 11:12

jldupont