多核编程中的mutex问题

shaotine_wu 2009-09-27 04:50:11
#define THREAD_NUMBER 2
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
[color=#FF00FF]//线程1对mutex加锁[/color]
void*thread1(void*arg)
{
pthread_mutex_lock(&mutex);
printf("thread1 locked the mutex\n");
printf("thread1 is waiting for conditiond signal.....\n");
pthread_cond_wait(&cond,&mutex);
printf("thread1 received condition signal!\n");
pthread_mutex_unlock(&mutex);
printf("thread1 unlock the mutex!\n");
pthread_exit(NULL);
}

void *thread2(void*arg){
int i=0;
struct timeval old,new;
gettimeofday(&old);
new=old;
pthread_mutex_lock(&mutex);
printf("thread2 lock the mutex\n");
while(new.tv_sec-old.tv_sec<5){
sleep(1);
gettimeofday(&new);
i++;
printf("thread2 sleep %d seconds\n",i);
}
printf("thread1 calls pthread_cond_sigal.....\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
printf("thread2 unlocked the mutex\n");
pthread_exit(NULL);
}

int main(int argc,char *argv[]){
int i;
int ret_val;
pthread_t pt[THREAD_NUMBER];
ret_val=pthread_create(&pt[0],NULL,thread1,NULL);
if(ret_val!=0){
printf("pthread_create error!\n");
exit(1);
}
ret_val=pthread_create(&pt[1],NULL,thread2,NULL);
if(ret_val!=0){
printf("pthread_create error!\n");
exit(1);
}
for(i=0;i<THREAD_NUMBER;i++){
ret_val=pthread_join(pt[i],NULL);
if(ret_val!=0){
printf("pthread_join error!\n");
exit(1);
}
}
return 0;
}
输出的结果是:
thread1 locked the mutex
thread1 is waiting for conditiond signal.....
thread2 lock the mutex //为什么在thread1还没有对mutex解锁的时候,thread2能对mutex加锁呢????
thread2 sleep 1 seconds
thread2 sleep 2 seconds
thread2 sleep 3 seconds
thread2 sleep 4 seconds
thread2 sleep 5 seconds
thread1 received condition signal!
thread2 unlocked the mutex
thread1 received condition signal!
thread1 unlock the mutex!
还有就是pthread_join函数到底有什么用处,我看了书,不是很理解!!
请各位帮忙解答!!谢谢
...全文
110 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
shaotine_wu 2009-10-18
  • 打赏
  • 举报
回复
谢谢oyster2008,我懂了!!!
oyster2008 2009-09-27
  • 打赏
  • 举报
回复
pthread_cond_wait会释放mutex上的锁并且使调用线程等待条件cond,当这个函数返回之后,调用线程会重新拥有mutex上的锁
oyster2008 2009-09-27
  • 打赏
  • 举报
回复
pthread_cond_wait(&cond,&mutex); 这个函数会释放锁
oyster2008 2009-09-27
  • 打赏
  • 举报
回复
pthread_join等待一个线程退出

70,037

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧