- 论坛徽章:
- 0
|
两个线程,CtrlThread线程控制PlayThread线程的开始和停止。
但是运行不了我期望的结果。
CtrlThread 中调用后stop之后,PlayThread依然在运行,停不了 ……
请问类似这样一个线程控制另外一个线程一般要怎么做?
- #include <pthread.h>
- #include <stdio.h>
- #include <unistd.h>
- pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
- pthread_t ctrlTid;
- pthread_t playTid;
- void start()
- {
- qDebug("start 1\n");
- pthread_mutex_unlock(&lock);
- qDebug("start 2\n");
- }
- void play()
- {
- pthread_mutex_lock(&lock);
- qDebug("playing\n");
- sleep(1);
- pthread_mutex_unlock(&lock);
- }
- void stop()
- {
- qDebug("stop 1\n");
- pthread_mutex_lock(&lock);
- qDebug("stop 2\n");
- }
- void * CtrlThread(void * argv)
- {
- qDebug("CtrlThread 1\n");
- sleep(1);
- start();
- sleep(5);
- stop();
- sleep(20);
- start();
- sleep(5);
- stop();
- qDebug("CtrlThread 2\n");
- return NULL;
- }
- void * PlayThread(void * argv)
- {
- qDebug("PlayThread 1\n");
- while (true)
- {
- play();
- }
- qDebug("PlayThread 2\n");
- return NULL;
- }
- int main(int argc, char *argv[])
- {
- pthread_mutex_lock(&lock);
- pthread_create(&ctrlTid,NULL,CtrlThread,NULL);
- pthread_create(&playTid,NULL,PlayThread,NULL);
- pthread_join(ctrlTid,NULL);
- pthread_join(playTid,NULL);
- return 0;
- }
复制代码 |
|