- 论坛徽章:
- 0
|
20可用积分
我看到下面一段多线程的小程序。这个程序创建两个线程,都检查一个变量,符合条件就继续执行。程序启动以后,先后执行了thread1和thread2.
我的问题是
1. pthread_cond_wait在thread1中到底被执行了多少次? 是一次还是无数次? 从执行结果来看是1次,但是既然是在while循环的内部,那么应该是执行了无数次才对吧? 难道pthread_cond_wait会用阻塞的方式去监视Number变量?
我不能理解那个while循环是如何工作的。
2. thread1和thread2的执行顺序是固定的呢还是随机的呢?
谢谢,源代码如下:
----------------------------------------
#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>
using namespace std;
int Number = 0;
pthread_mutex_t NMutex;
pthread_cond_t NCond;
void *thread1(void *arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&NMutex);
while (Number <= 0 ){
cout<<"t1"<<endl;
pthread_cond_wait(&NCond, &NMutex);
}
int Count = Number;
int Sum = 1;
for (int i = 1; i < Count; i++)
Sum += i;
cout << "count by thread1 is " << Sum << endl;
pthread_mutex_unlock(&NMutex);
return NULL;
}
void *thread2(void *arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&NMutex);
while (Number <= 0 )//等待主线程读入Number
pthread_cond_wait(&NCond, &NMutex);
int Count = Number;
int Sum = 1;
for (int i = 1; i < Count; i++)
Sum += i;
cout << "count by thread2 is " << Sum << endl;
pthread_mutex_unlock(&NMutex);
return NULL;
}
int main(int argc, char* argv[])
{
pthread_mutex_init(&NMutex, NULL);
pthread_cond_init(&NCond, NULL);
pthread_t p1, p2;
pthread_create(&p1, NULL, thread1, NULL);
pthread_create(&p2, NULL, thread2, NULL);
//begin input
pthread_mutex_lock(&NMutex);
cout << "input a number ";
cin >> Number;
pthread_mutex_unlock(&NMutex);
pthread_cond_signal(&NCond);
//end input
pthread_exit(NULL);
} |
最佳答案
查看完整内容
1.pthread_cond_wait确实是阻塞方式的,它是用pthread_cond_signal来唤醒的撒。whiile循环中的原理就是取得互斥量,如果符合whiile的条件,进入循环,释放互斥量,阻塞在pthread_cond_wait。被pthread_cond_signal唤醒后,继续程序流程,再次检查while的条件,如此。。。2.随即的
|