题目:文章来源:https://www.toymoban.com/news/detail-626491.html
- 创建三个线程 id号为ABC,三个线程循环打印自己的ID号,运行顺序为 ABCABC......
- 要求使用条件变量
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//创建互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//条件变量创建
pthread_cond_t cond1 =PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 =PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 =PTHREAD_COND_INITIALIZER;
//限制访问机制
int flag=1;
void* callback1(void* arg)
{
while(1)
{
/*************临界区**************/
//上锁
pthread_mutex_lock(&mutex);
if(flag != 1)
{
//休眠 解锁
pthread_cond_wait(&cond1,&mutex);
}
printf("A");
flag=2;
//唤醒
pthread_cond_signal(&cond2);
//解锁
pthread_mutex_unlock(&mutex);
/*************临界区**************/
}
pthread_exit(NULL);
}
void* callback2(void* arg)
{
while(1)
{
/*************临界区**************/
//上锁
pthread_mutex_lock(&mutex);
if(flag != 2)
{
//休眠 解锁
pthread_cond_wait(&cond2,&mutex);
}
printf("B");
flag=3;
//唤醒
pthread_cond_signal(&cond3);
//解锁
pthread_mutex_unlock(&mutex);
/*************临界区**************/
}
pthread_exit(NULL);
}
void* callback3(void* arg)
{
while(1)
{
/*************临界区**************/
//上锁
pthread_mutex_lock(&mutex);
if(flag != 3)
{
//休眠 解锁
pthread_cond_wait(&cond3,&mutex);
}
printf("C\n");
flag=1;
//唤醒
pthread_cond_signal(&cond1);
//解锁
pthread_mutex_unlock(&mutex);
/*************临界区**************/
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//练习1.创建三个线程id号为ABC,要求三个线程循环打印自己的ID号, 运行顺序为ABCAB.....
pthread_t A,B,C;
if(pthread_create(&A,NULL,callback1,NULL)!=0)
{
fprintf(stderr,"pthread_create faild __%d__\n",__LINE__);
return -1;
}
if(pthread_create(&B,NULL,callback2,NULL)!=0)
{
fprintf(stderr,"pthread_create faild __%d__\n",__LINE__);
return -1;
}
if(pthread_create(&C,NULL,callback3,NULL)!=0)
{
fprintf(stderr,"pthread_create faild __%d__\n",__LINE__);
return -1;
}
pthread_join(A,NULL);
pthread_join(B,NULL);
pthread_join(C,NULL);
//销毁互斥锁
pthread_mutex_destroy(&mutex);
//销毁条件变量
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
pthread_cond_destroy(&cond3);
return 0;
}
运行结果:死循环输出ABC\n文章来源地址https://www.toymoban.com/news/detail-626491.html
ubuntu@ubuntu:04_pthread$ gcc t3.3pthread.c -pthread
ubuntu@ubuntu:04_pthread$ ./a.out
ABC
ABC
ABC
ABC
ABC
到了这里,关于【练习】条件变量:创建三个线程 id号为ABC,三个线程循环打印自己的ID号,运行顺序为 ABCABC的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!