由于条件变量必须和互斥锁协同使用,所以在介绍条件前会先介绍一下互斥锁(本文目前只介绍C语言,C++的条件变量可能后期会介绍)

1、互斥锁

从本质上来说,互斥锁是一把锁,保护共享资源免受并发影响的问题,同一时间只能有一个线程可以访问被保护的资源,从而防止竞态而产生不好的结果

1、C语言互斥锁的基本使用

pthread_mutex_init:初始化

pthread_mutex_lock:上锁

pthread_mutex_trylock:如果mutex已经被其他线程上锁,该操作会一直阻塞在这个地方,如果不想一直阻塞在这个地方,trylock若此时互斥量没有被上锁,函数会返回0,并对该互斥量进行上锁,如果被上锁了,就立刻返回ebusy

pthread_mutex_unlock:解锁

2、条件变量

1、引入的原因

互斥锁存在的问题:明显的缺点就是它只有锁定和非锁定两种状态,多个线程同时访问一个共享资源,并不知道合适应该使用共享资源,在临界区增加判断语句,效率不高且难实现,而条件变量能在条件成立时触发相应的线程,进行变量的修改和访问

条件变量通过允许线程阻塞和等待另一个线程发送信号的方法弥补了互斥锁的不足,常和互斥锁一起使用

2、基本函数

pthread_cond_init:创建

pthread_cond_singal:激活一个等待等待该条件的线程

pthread_cond_broadcast:激活所有等待的线程

pthread_cond_wait:等待

pthread_cond_timewait:在限定的时间内等待

pthread_cond_destory:销毁

相关示例

#include

#include

#include

pthread_mutex_t mutex;

pthread_cond_t isthree;

int i = 1;

void* thread1(void* arg)

{

for (i = 1; i <= 9; i++)

{

pthread_mutex_lock(&mutex);

if (i % 3 == 0)

{

pthread_cond_signal(&isthree);

}

else

{

printf("this is thread1 i is: %d\n", i);

}

pthread_mutex_unlock(&mutex);

sleep(1);

}

}

void* thread2(void* arg)

{

printf("aaaa\n");

while (i <= 9)

{

pthread_mutex_lock(&mutex);

if (i % 3 != 0)

{

pthread_cond_wait(&isthree, &mutex);

printf("this is thread2 i is: %d\n", i);

}

pthread_mutex_unlock(&mutex);

sleep(1);

}

}

int main()

{

pthread_mutex_init(&mutex, NULL);

pthread_cond_init(&isthree, NULL);

pthread_t t1;

pthread_t t2;

pthread_create(&t1, NULL, thread1, NULL);

pthread_create(&t2, NULL, thread2, NULL);

pthread_join(t2, NULL);

pthread_mutex_destroy(&mutex);

pthread_cond_destroy(&isthree);

return 0;

}