一个简单的互斥量与条件变量例子
#include <pthread.h> #include <stdio.h> #include <stdlib.h> //互斥变量和条件变量静态初始化 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;/*初始化互斥锁*/ pthread_cond_t cond = PTHREAD_COND_INITIALIZER;/*初始化条件变量*/ void *thread1(void *); void *thread2(void *); int i=1; int main(void) { // sleep(30); pthread_t t_a; pthread_t t_b; pthread_create(&t_a,NULL,thread1,(void *)NULL);/*创建进程t_a*/ pthread_create(&t_b,NULL,thread2,(void *)NULL); /*创建进程t_b*/ pthread_join(t_a, NULL);/*等待进程t_a结束*/ pthread_join(t_b, NULL);/*等待进程t_b结束*/ pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); exit(0); } /* pthread_t pthread_self(void); 函数作用:获得线程自身的ID。 pthread_t的类型为unsigned long int, 所以在打印的时候要使用%lu方式,否则将产生奇怪的结果 */ void *thread1(void *junk) { for(i=1;i<=6;i++) { pthread_mutex_lock(&mutex);/*锁住互斥量*/ { printf("Thread1: lock ------%lu\n", pthread_self()); } if(i%3==0) { printf("Thread1:signal1------%lu\n", pthread_self()); pthread_cond_signal(&cond);/*条件改变,发送信号,通知t_b进程*/ printf("Thread1:signal2------%lu\n", pthread_self()); sleep(1); } pthread_mutex_unlock(&mutex);/*解锁互斥量*/ printf("Thread1: unlock ------%lu\n", pthread_self()); sleep(1); } } void *thread2(void *junk) { while(i<6) { pthread_mutex_lock(&mutex); printf("Thread2: lock ------%lu\n", pthread_self()); if(i%3!=0) { printf("Thread2: wait1------%lu\n", pthread_self()); pthread_cond_wait(&cond,&mutex);/*解锁mutex,并等待cond改变*/ printf("Thread2: wait2------%lu\n", pthread_self()); } pthread_mutex_unlock(&mutex); printf("Thread2: unlock ------%lu\n", pthread_self()); sleep(1); } } /* [ztteng@ztteng 7.7_8]$ ./pthreadcond Thread2: lock ------3068291952 Thread2: wait1------3068291952 Thread1: lock ------3078781808 Thread1: unlock ------3078781808 Thread1: lock ------3078781808 Thread1: unlock ------3078781808 Thread1: lock ------3078781808 Thread1:signal1------3078781808 Thread1:signal2------3078781808 Thread1: unlock ------3078781808 Thread2: wait2------3068291952 Thread2: unlock ------3068291952 Thread1: lock ------3078781808 Thread1: unlock ------3078781808 Thread2: lock ------3068291952 Thread2: wait1------3068291952 Thread1: lock ------3078781808 Thread1: unlock ------3078781808 Thread1: lock ------3078781808 Thread1:signal1------3078781808 Thread1:signal2------3078781808 Thread1: unlock ------3078781808 Thread2: wait2------3068291952 Thread2: unlock ------3068291952 */

这里有几个问题;(1)一个是为什么是thread2先执行(2)假若thread1先执行;并发送了signal信号,这时thread2还没有起来会怎么样

浙公网安备 33010602011771号