两个线程执行一次打印一次数据并加一。让t2先执行,然后t1再执行一次。
代码:
#include<stdio.h>
#include<pthread.h>
//int pthread_create(pthread_t *restrict 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 *argc)
{
printf("t1:%ld thread is created!\n",(unsigned long)pthread_self());
printf("t1:param id %d\n",*((int *)argc));
while(1)
{
pthread_cond_wait(&cond,&mutex);//等待
printf("t1 run ===========================\n");
printf("t1:%d\n",g_data);
g_data=0;
sleep(1);
}
}
void *func2(void *argc)
{
printf("t2:%ld thread is created!\n",(unsigned long)pthread_self());
printf("t2:param id %d\n",*((int *)argc));
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_t t1;
pthread_t t2;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);//创建
ret = pthread_create(&t1,NULL,func1,(void *)¶m);
ret = pthread_create(&t2,NULL,func2,(void *)¶m);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);//销毁
return 0;
}
看看结果:
t1执行两句后就一直在等待触发,t2正常表演。
用宏的话为静态初始化上面为动态初始化
静态:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
int g_data=0;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void *func1(void *argc)
{
static int cnt =0;
printf("t1:%ld thread is created!\n",(unsigned long)pthread_self());
printf("t1:param id %d\n",*((int *)argc));
while(1)
{
pthread_cond_wait(&cond,&mutex);
printf("t1 run ===========================\n");
printf("t1:%d\n",g_data);
g_data=0;
sleep(1);
if(cnt++==5)
{
exit(0);
}
}
}
void *func2(void *argc)
{
printf("t2:%ld thread is created!\n",(unsigned long)pthread_self());
printf("t2:param id %d\n",*((int *)argc));
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_t t1;
pthread_t t2;
// pthread_mutex_init(&mutex,NULL);
// pthread_cond_init(&cond,NULL);
ret = pthread_create(&t1,NULL,func1,(void *)¶m);
ret = pthread_create(&t2,NULL,func2,(void *)¶m);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
~
也可
版权声明:本文为qq_43482790原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。