I am developing an application. In which I do multithreading. One of my worker thread display images on the widget. Another thread play sound. I want to stop/suspend/pause/sleep the threads on 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. I use pthread library for threading. Can somebody tell me how I achieve threads pause/suspend.
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.
You can do it using shared memory by having a (for example) "play sound" flag somewhere, having the sound thread check it periodically and when it's off just sleep for a while and then check again. Disadvantage of this approach is that the thread would do some (minimal) work even when it's off.
The other approach is to use a mutex istead of flag. Playback thread would acquire and release the mutex periodically, and if you wanted to pause the thread, all you have to do is acquire the mutex. As lock as the control thread has the mutex, playback thread would be waiting.
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 */
if(!play) { /* We're paused */
pthread_mutex_lock(&lock);
while(!play) { /* Still paused */
/* Wait for play signal */
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:
play = 0;