- /*********************************************************************************
- *
- * 设计程序,创建三个线程,任务1条件满足时解除任务二的挂起状态,任务3用于控制x的值
- * author:jindouliu2024@163.com
- * date:2025.5.12
- *
- *
- * Copyright (c) 2024-2025 jindouliu2024@163.com All right Reserved
- ********************************************************************************/
复制代码- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- pthread_t task1_id;
- pthread_t task2_id;
- pthread_t task3_id;
- pthread_t main_id;
- int x = 10,y = 20;
- pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
- void * task1(void *arg)
- {
-
- while(1){
- //上锁
- pthread_mutex_lock(&mutex);
- //如果不满足,则一直阻塞等待
- while(x <= y){
- printf("running1\n");
- pthread_cond_wait(&cond,&mutex);
- }
- //如果满足,则通知唤醒
- pthread_cond_broadcast(&cond);
- //解锁
- pthread_mutex_unlock(&mutex);
-
- }
- pthread_exit(NULL);
- }
- void * task2(void *arg)
- {
-
- while(1){
- //上锁
- pthread_mutex_lock(&mutex);
- printf("running2\n");
- //如果不满足,则一直阻塞等待
- if(x > y){
- printf("条件满足\n");
- pthread_cond_broadcast(&cond);
- }
- //解锁
- pthread_mutex_unlock(&mutex);
- sleep(1);
- }
- pthread_exit(NULL);
- }
- void * task3(void *arg)
- {
-
- while(1){
- //上锁
- pthread_mutex_lock(&mutex);
- if(x > y){
- y += 10;
- }
- x += 2;
- printf("running3\n");
-
- //解锁
- pthread_mutex_unlock(&mutex);
- sleep(1);
- }
- pthread_exit(NULL);
- }
- int main()
- {
- //初始化条件变量
- pthread_cond_init(&cond,NULL);
- //初始化互斥锁
- pthread_mutex_init(&mutex,NULL);
- //设置主线程为可分离属性
- pthread_detach(pthread_self());
- //pthread_t task1_id,task2_id,main_id;
- //定义线程属性对象
- pthread_attr_t thread_arr;
- //初始化线程属性对象
- pthread_attr_init(&thread_arr);
- //设置线程属性
- pthread_attr_setdetachstate(&thread_arr,PTHREAD_CREATE_DETACHED);
- //使用线程属性创建线程
- pthread_create(&task1_id,&thread_arr,task1,NULL);
- pthread_create(&task2_id,&thread_arr,task2,NULL);
- pthread_create(&task3_id,&thread_arr,task3,NULL);
- //主线程退出
- pthread_exit(NULL);
- return 0;
- }
复制代码 来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |