5.线程与并发同步-使用条件变量实现两个线程之间的同步

本文通过一个实例展示了如何利用条件变量在两个线程间实现同步,线程1负责打印9以内非3的倍数,线程2则打印3的倍数。通过示例代码的运行结果,可以看到线程间的正确同步执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程1打印9以内不是3的倍数,线程2打印3的倍数

#include<pthread.h>
#include<stdio.h>
#include<unistd.h>

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int i=1;

void *t1(void*arg){
    for(;i<=9;i++){
		pthread_mutex_lock(&mutex);
		if(i%3==0){
			//pthread_cond_signal(&cond);
            pthread_cond_broadcast(&cond);
		}
		else{
			printf("thread 1 : %d\n",i);
		}
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
}

void *t2(void*arg){

   
    
    for(;i<9;){	
        pthread_mutex_lock(&mutex); 
        printf("pthread 2 lock\n");
		while(i%3!=0)
		{
            pthread_cond_wait(&cond,&mutex);
            printf("pthread 2 cond_wait return \n");
            printf("thread 2 : %d\n",i);
        }
		
		
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
}

int main(){
	
	pthread_t p1,p2;
	pthread_create(&p1,NULL,t1,NULL);
	pthread_create(&p2,NULL,t2,NULL);
	pthread_join(p1,NULL);
	pthread_join(p2,NULL);
	
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
	
	return 0;
}


gdut17@ubuntu:~/code/0227$ sudo gcc cond.c -pthread
gdut17@ubuntu:~/code/0227$ ./a.out
pthread 2 lock
thread 1 : 1
thread 1 : 2
pthread 2 cond_wait return
thread 2 : 3
pthread 2 lock
thread 1 : 4
pthread 2 lock
thread 1 : 5
pthread 2 cond_wait return
thread 2 : 6
pthread 2 lock
thread 1 : 7
pthread 2 lock
thread 1 : 8
pthread 2 cond_wait return
thread 2 : 9
gdut17@ubuntu:~/code/0227$

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值