如何在 Linux 上的 c 中休眠或暂停 PThread
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1606400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sleep or pause a PThread in c on Linux
提问by Muhammad Ummar
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.
我正在开发一个应用程序,我在其中执行多线程。我的一个工作线程在小部件上显示图像。另一个线程播放声音。我想停止/暂停/暂停/休眠按钮单击事件上的线程。这与我们点击视频播放器播放/暂停按钮时相同。我正在 linux 平台上使用 pthread 库在 c++ 中开发我的应用程序进行线程处理。
Can somebody tell me how I achieve threads pause/suspend?
有人能告诉我如何实现线程暂停/暂停吗?
回答by LnxPrgr3
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);
回答by jldupont
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.
您让您的线程定期从 UI 轮询“消息”。换句话说,一个线程中的 UI 将操作消息发布到工作线程,例如音频/视频。