刚出来找工作,面试官问我怎么实现三条线程,分别打印A,B,C,但是看到输出来的结果是ABCABC……这样子,当时我第一反应是用信号量呀。他反问那你需要创多少个?没细想,其实三个就行了(有名信号量的话),那语气我还以为不行。又想了一会说信号(signal)可以吧,他说可以,但是我用的又不太熟呀,调试着写估计能成,现场说不出来……最后问了其他人,原来那面试官想要我用条件变量和互斥锁来实现……我会呀,说个思路完全没问题,但是可能需要翻资料琢磨着写,太久不用了……就想吐槽,能不能好好说话,就不能提示一下,你如果用条件变量来实现呢?……回来马上就写了出来,越想越不太对呀,理论上信号,SPI对象都是用来线程间交流的呀,它关键不就等一个线程操作完通知下一个嘛?我这个思路没问题呀
三条线程轮流打印ABC
C语言,条件变量互斥锁实现
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t m; //互斥锁
pthread_cond_t v; //条件变量
int input = 0; //打印端口就绪
void *thread1(void *args)
{
pthread_mutex_lock(&m); //上锁
for(int i=0;i<10; i++)
{
while(input != 1)
pthread_cond_wait(&v, &m); //否则,进入等待队列,自带解锁
printf("A\n"); //打印
input = 2;
pthread_cond_broadcast(&v); //唤醒所有线程
}
pthread_mutex_unlock(&m); //解锁
return NULL;
}
void *thread2(void *args)
{
pthread_mutex_lock(&m); //上锁
for(int i=0;i<10; i++)
{
while(input != 2)
pthread_cond_wait(&v, &m); //否则,进入等待队列
printf("B\n"); //打印
input = 3;
pthread_cond_broadcast(&v); //唤醒所有线程
}
pthread_mutex_unlock(&m); //解锁
return NULL;
}
void *thread3(void *args)
{
pthread_mutex_lock(&m); //上锁
for(int i=0;i<10; i++)
{
while(input != 3)
pthread_cond_wait(&v, &m); //否则,进入等待队列
printf("C\n"); //打印
input = 1;
pthread_cond_broadcast(&v); //唤醒所有线程
}
pthread_mutex_unlock(&m); //解锁
return NULL;
}
int main()
{
printf("Input ABC text\n");
//初始化互斥锁和条件变量
pthread_mutex_init(&m, NULL);
pthread_cond_init(&v, NULL);
//打开打印开关,通知所有在条件队列的线程
pthread_mutex_lock(&m);
input = 1; //打开端口
pthread_cond_signal(&v);
pthread_mutex_unlock(&m);
//创建3条线程,并等待其结束
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, thread1, NULL);
pthread_create(&tid2, NULL, thread2, NULL);
pthread_create(&tid3, NULL, thread3, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
//销毁互斥锁和条件变量
pthread_mutex_destroy(&m);
pthread_cond_destroy(&v);
//退出
return 0;
}