在使用线程的时候,通常需要对多线程惊醒条件判断实现同步控制,这里就得用到与线程条件相关的API。即线程的等待和触发,注:条件变量使用前必须先初始化。
相关代码如下:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
// int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
int date=0;
pthread_mutex_t mutex; //互斥锁相关变量
pthread_cond_t cound; //定义线程条件变量
void* func1(void* arg)
{
static int cnt=0;
static char *p="th1 quit";
printf("This is create thread;and thread ID:%ld\n",(unsigned long)pthread_self());
printf("pream is :%d\n",*((int*)arg));
pthread_mutex_lock(&mutex);
while(1)
{
pthread_cond_wait(&cound,&mutex); //线程等待触发
printf("=============t1 run=============\n");
printf("t1date=%d\n",date);
date=0;
sleep(1);
if(cnt==10)
{
exit(1);
}
cnt++;
}
}
void* func2(void* arg)
{
static char *p="th1 quit";
printf("This is create thread;and thread ID:%ld\n",(unsigned long)pthread_self());
printf("pream is :%d\n",*((int*)arg));
while(1)
{
printf("t2date=%d\n",date);
pthread_mutex_lock(&mutex);
date++;
if(date==3)
{
pthread_cond_signal(&cound); //线程触发,th1开始执行
}
pthread_mutex_unlock(&mutex); //互斥锁打开
sleep(1);
}
}
int main()
{
pthread_t th1;
pthread_t th2;
int pream=100;
pthread_mutex_init(&mutex,NULL); //初始化互斥锁
pthread_cond_init(&cound,NULL); //初始化条件变量
int point1=pthread_create(&th1,NULL,func1,(void*)&pream);
int point2=pthread_create(&th2,NULL,func2,(void*)&pream);
if(point1==0)
{
// printf("This is main thread,and mainthread ID is %ld\n",(unsigned long)pthread_self());
}
pthread_join(th1,NULL);
pthread_join(th2,NULL);
pthread_mutex_destroy(&mutex); //销毁互斥锁
pthread_cond_destroy(&cound); //销毁条件变量
return 0;
}
测试小技巧:
当代码需要做测试的时候,我们可以写一个shell脚本或者直接写出一个程序来控制要执行的代码执行多少遍,然后生成一个测试文件,以上文代码为例,我们可以写出一个程序:
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char** argv)
{
int time=atoi(argv[1]);
int i;
for(i=0;i<time;i++)
{
system("./demo");
}
return 0;
}
然后调用它,dmoe4是上文文件名
./a.out 10 >>test.ret.txt &
上文代码就会执行十遍后保存在test.ret.txt文件中。