当前位置: 代码迷 >> 多核软件开发 >> 一个简单的线程同步有关问题,求解
  详细解决方案

一个简单的线程同步有关问题,求解

热度:7090   发布时间:2013-02-26 00:00:00.0
一个简单的线程同步问题,求解
问题:一个线程让count从1变化到100,每加10(count%10==0),就通知另一个线程输出相应的信息
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
int count=0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* thread1(void*);
void* thread2(void*);
int main(int argc, char** argv)
{
pthread_t tid1, tid2;
  pthread_mutex_init(&mutex, NULL); 
  pthread_cond_init(&cond,NULL);
pthread_create(&tid1, NULL, thread1, &tid2);
pthread_create(&tid2, NULL, thread2, NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
exit(0);
}
void* thread1(void* arg)
{
int i=0;
for(i=0;i<100;i++){
pthread_mutex_lock(&mutex);
count++;
if(count%10==0){
  printf("t1: %d\n",count);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
  sleep(1); //让线程2有时间输出
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void* thread2(void* arg)
{
int i=1;
while(1){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
printf("count is up to %d \n",10*i++);
if(count>=100)break;
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
输出结果
t1: 10
t1: 20
count is up to 10 
t1: 30
count is up to 20 
t1: 40
count is up to 30 
t1: 50
count is up to 40 
t1: 60
count is up to 50 
t1: 70
count is up to 60 
t1: 80
count is up to 70 
t1: 90
count is up to 80 
t1: 100
count is up to 90 
为什么在count到了10之后线程2没接到通知?即:输出应该是
t1: 10
然后输出count is up to 10 
但程序不管怎样都是线程1运行到20才开始输出,不得解啊

------解决方案--------------------------------------------------------
t1:10
count is up to 10
t1:20
count is up to 20
t1:30
count is up to 30
t1:40
count is up to 40
t1:50
count is up to 50
t1:60
count is up to 60
t1:70
count is up to 70
t1:80
count is up to 80
t1:90
count is up to 90
t1:100
count is up to 100

把thread1和thread2的内容互换一下,就可以得到楼主想要的结果了。至于原因我想是当signal第一次执行的时候,thread2并没有执行即没有wait()被执行,所以没有唤醒操作,因此没有执行打印语句,后来,thread2得到cpu开始执行,此时,才有wait()操作
------解决方案--------------------------------------------------------
问题搞清楚,哪个线程先跑了。。。
thread1先跑:
t1: 10
t1: 20
count is up to 10 
thread2先跑:
t1:10
count is up to 10
t1:20
没有任何问题。可以分别在每个线程函数开始sleep(1) try下
  相关解决方案