首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

条件变量的作用?请问

2012-03-16 
条件变量的作用??请教前一阵学习posix多线程,对互斥锁 和条件变量 有些了解了,可是最近突然有个困惑,就是

条件变量的作用??请教
前一阵学习posix多线程,对互斥锁 和条件变量 有些了解了,可是最近突然有个困惑,就是条件变量的功能到底是什么,也就是说,只用互斥锁 与 同时用互斥锁和条件变量的区别在哪?
一段代码如下:

C/C++ code
#include <stdio.h>   #include<pthread.h> //多线程所用头文件#include <semaphore.h> //信号量使用头文件pthread_cond_t g_cond /*=PTHREAD_MUTEX_INITIALIZER*/; //申明条锁,并用宏进行初始化pthread_mutex_t g_mutex ;//线程执行函数void threadFun1(void){  int i;  pthread_mutex_lock(&g_mutex); //1  pthread_cond_wait(&g_cond,&g_mutex); //如g_cond无信号,则阻塞  for( i = 0;i < 2; i++ ){  printf("thread threadFun1.\n");  sleep(1);  }  pthread_cond_signal(&g_cond);     pthread_mutex_unlock(&g_mutex);}int main(void){  pthread_t id1; //线程的标识符  pthread_t id2;  pthread_cond_init(&g_cond,NULL); //也可以程序里面初始化  pthread_mutex_init(&g_mutex,NULL); //互斥变量初始化  int i,ret;  ret = pthread_create(&id1,NULL,(void *)threadFun1, NULL);    if ( ret!=0 ) { //不为0说明线程创建失败  printf ("Create pthread1 error!\n");  return (1);  }  sleep(5); //等待子线程先开始  pthread_mutex_lock(&g_mutex); //2  pthread_cond_signal(&g_cond); //给个开始信号,注意这里要先等子线程进入等待状态在发信号,否则无效    printf("do something\n");  pthread_mutex_unlock(&g_mutex);       pthread_join(id1,NULL);         pthread_cond_destroy(&g_cond); //释放  pthread_mutex_destroy(&g_mutex); //释放      return 0;}


代码的工作流程我是可以了理解的,但是如果把条件变量去掉,也就是下面的代码:
C/C++ code
#include <stdio.h>   #include<pthread.h> //多线程所用头文件#include <semaphore.h> //信号量使用头文件pthread_cond_t g_cond /*=PTHREAD_MUTEX_INITIALIZER*/; //申明条锁,并用宏进行初始化pthread_mutex_t g_mutex ;//线程执行函数void threadFun1(void){  int i;  pthread_mutex_lock(&g_mutex); //1  //pthread_cond_wait(&g_cond,&g_mutex); //如g_cond无信号,则阻塞  for( i = 0;i < 2; i++ ){  printf("thread threadFun1.\n");  sleep(5);  }  pthread_cond_signal(&g_cond);     pthread_mutex_unlock(&g_mutex);}int main(void){  pthread_t id1; //线程的标识符  pthread_t id2;  pthread_cond_init(&g_cond,NULL); //也可以程序里面初始化  pthread_mutex_init(&g_mutex,NULL); //互斥变量初始化  int i,ret;  ret = pthread_create(&id1,NULL,(void *)threadFun1, NULL);    if ( ret!=0 ) { //不为0说明线程创建失败  printf ("Create pthread1 error!\n");  return (1);  }  sleep(3); //等待子线程先开始  pthread_mutex_lock(&g_mutex); //2      printf("do something\n");  //pthread_cond_signal(&g_cond); //给个开始信号,注意这里要先等子线程进入等待状态在发信号,否则无效  pthread_mutex_unlock(&g_mutex);       pthread_join(id1,NULL);         pthread_cond_destroy(&g_cond); //释放  pthread_mutex_destroy(&g_mutex); //释放      return 0;}


我的意思是,反正一个线程解锁(可能要再sleep一下),另一个线程就能获得锁,那还要用条件变量干嘛用呢?



[解决办法]
那如果两个线程需要同时访问一个资源呢?或者一个线程正在对一个全局信息进行操作的时候,另外一个线程也开始对其操作了呢?
锁或者条件变量的作用很重要呢,特别是多线程并发运行的时候。
对线程的概念好好理解一下。

热点排行