Linux线程条件控制实现线程的同步
多线程操作相关概念参考Linux多线程编程初探 - 峰子_仰望阳光 - 博客园 (cnblogs.com)
demo6.c
#include<stdio.h>
#include<pthread.h>
//int pthread_create(pthread_t *restricti tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
int g_data = 0;//全局变量
pthread_mutex_t mutex;
pthread_cond_t cond;
void *func1(void *arg)//线程1
{
printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
printf("t1:param is %d\n",*((int *)arg));
static int cnt =0;//线程返回值一般定义为static int XX
while(1){
pthread_cond_wait(&cond,&mutex);//线程条件等待
printf("run======================\n");
printf("t1: %d\n",g_data);
g_data =0;
sleep(1);
if(cnt++ ==10){//运行十次
exit(1);
}
}
}
void *func2(void *arg)//线程2
{
printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
printf("t2:param is %d\n",*((int *)arg));
while(1){
printf("t2: %d\n",g_data);
pthread_mutex_lock(&mutex);
g_data++;
if(g_data ==3){
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()//主函数
{
int ret;
int param =100;
pthread_mutex_init(&mutex,NULL);
pthread_t t1;
pthread_t t2;
ret =pthread_create(&t1,NULL,func1,(void *)¶m);
if(ret ==0){
// printf("main:create t1 success!\n");
}
ret =pthread_create(&t2,NULL,func2,(void *)¶m);
if(ret ==0){
// printf("main:create t2 success!\n");
}
// printf("main:%ld \n",(unsigned long)pthread_self());
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
测试:创建一个test1.c
int main(int argc,char **argv)`
`{`
int time=atoi(argv[1]);
int i=0;
for(i=0;i<time;i++){
system("./demo6");
}
`}`
将测试结果写入test.ret.txt,执行命令依次为:gcc demo6.c -pthread -o demo6->gcc test1.c->./a.out 10 >>test.ret.txt &(注意“&”作用是将改该程序放在后台运行)
打开test.ret.txt即可查看运行结果如下:
后续跟进:1、Linux线程编程之生产者消费者问题
面试问题:cond linux 线程 初始化 宏相关内容可参考:
LINUX线程之一次性初始化(PTHREAD_ONCE) - ⭐⭐-fighting⭐⭐ - 博客园 (cnblogs.com)
pthread_cond_t cond;
//动态初始化: pthread_cond_init(&cond, NULL);
//静态初始化: pthread_cond_t = PTHREAD_COND_INITIALIZER;
pthread_mutex_t;
//动态初始化: pthread_mutex_init(&mutex,NULL);
//静态初始化: pthread_mutex_t = PTHREAD_MUTEX_INITIALIZER;
补充线程死锁概念:什么时候会陷入死锁?
例如:线程1手里拿着锁a,线程2拿着锁b,接下来线程1想要线程2手中的锁b,同时线程2想要线程手中的锁a,在这种情况下会造成线程之间的死锁。