思路:就是来回的利用pthread_cond_signal()函数,当一方被阻塞时,唤醒函数可以唤醒pthread_cond_wait()函数,只不过pthread_cond_wait()这个方法要执行其后的语句,必须遇到下一个阻塞(也就是pthread_cond_wait()方法时),才执行唤醒后的其后语句。
代码如下:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#define MAX_NUM 2
static int count = 1;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t js = PTHREAD_COND_INITIALIZER;
pthread_cond_t os = PTHREAD_COND_INITIALIZER;
void* A(void *arg){
pthread_mutex_lock(&mutex);
while(count <= MAX_NUM){
if(count%2 == 1){
printf("A = %d\n", count);
count++;
pthread_cond_signal(&os);
sleep(5);
printf("bbbbbbbbbbbbbbbbbbbbbbbbbbb\n");
}else{
printf("ccccccccccccccccccccccccccc\n");
pthread_cond_wait(&js, &mutex);
printf("ddddddddddddddddddddddddddd\n");
}
pthread_mutex_unlock(&mutex);
}
}
void* B(void *arg){
pthread_mutex_lock(&mutex);
while(count <= MAX_NUM){
if(count%2 == 0){
printf("B = %d\n", count);
count++;
pthread_cond_signal(&js);
}else{
pthread_cond_wait(&os, &mutex);
printf("aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n");
}
}
pthread_mutex_unlock(&mutex);
}
int main(void){
pthread_t tid1, tid2;
pthread_create(&tid2, NULL, B, NULL);
sleep(1);
pthread_create(&tid1, NULL, A, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
运行结果:
上面的这个程序就是:2个条件变量对一个互斥量的操作。signal()发送唤醒wait(),wait()之后的语句暂时不执行,直到下一次遇到wait()时,阻塞,返回执行唤醒的wait()之后的语句。
利用2个条件变量和1个互斥量即可实现。
代码如下:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
void* thread_fun1(void *arg){
int i = *(int *)arg;
pthread_mutex_lock(&mutex);
printf("[%d] thread start up\n", i);
pthread_cond_wait(&cond, &mutex);
printf("[%d]thread is wake up\n", i);
pthread_mutex_unlock(&mutex);
}
void* thread_fun2(void *arg){
pthread_cond_broadcast(&cond); //广播,一次唤醒所有的线程
}
int main(void){
pthread_t tid1[10], tid2;
int i;
for(i = 0; i < 10; i++){
pthread_create(&tid1[i], NULL, thread_fun1, &i);//创建10个线程
sleep(1);
}
pthread_create(&tid2, NULL, thread_fun2, NULL);//创建1个线程
for(i = 0; i < 10; i++){ //主线程等子线程执行完
pthread_join(tid1[i], NULL);
}
pthread_join(tid2, NULL);
return 0;
}
运行结果:
多线程的编程中:互斥量、条件变量是重中之重!!!