Linux系统编程(19)——同步

同步

同步控制着线程和线程之间的执行顺序。(主要是抢占式执行惹的祸,有的时候需要线程和线程之间按照一定的顺序来执行)。

相关函数: 

位置在主函数中:

pthread_cond_init(&cond,NULL):初始化同步

pthread_cond_destory(&mutex):释放同步

定义全局函数位置定义:

pthread_cond_t cond:定义一个同步

需要同步的位置:

pthread_cond_wait(&cond,&mutex):等待,放在需要等待的函数中,注意配合锁使用

pthread_cond_signal(&cond):通知等待的函数,放在快的那个函数中,要通知等待的函数开始运行


为什么 pthread_cond_wait()函数 要配合锁使用?

pthread_cond_wait()函数做了什么:

  1. 先释放锁
  2. 等待条件就绪
  3. 重新获取锁,准备执行后续的操作

1 和 2 必须是原子的,因为要避免其他线程的通知消息没收到,傻等,所以他俩不可拆分的。而这个不分开的操作就是缘子操作


代码示例:

#include <stdio.h>
#include<pthread.h> //头文件
#include <unistd.h>  //sleep头文件


#define THERAD_NUM 1

//定义一个互斥锁
pthread_mutex_t mutex;
//条件变量基础使用——同步
pthread_cond_t cond;

int g_count = 0;

void* ThreadEntry1(void* arg) {  //新线程入口,参数
	(void)arg;
	while (1) {
		printf("传球\n");
		pthread_cond_signal(&cond);	//通知等待的函数
		usleep(678678);
	}
	return NULL;
}

void* ThreadEntry2(void* arg) {  //新线程入口,参数
	(void)arg;
	while (1) {
		//执行这个pthread_cond_wait就会使线程阻塞,什么时候结束?一直等待线程发送通知,就是pthread_cond_signal函数
		pthread_cond_wait(&cond, &mutex);//等待
		printf("扣篮\n");
		usleep(123999);
	}
	return NULL;
}

int main() {

	pthread_mutex_init(&mutex, NULL);//互斥锁初始化函数
	pthread_cond_init(&cond, NULL);//同步初始化函数

	pthread_t tid1,tid2;

	pthread_create(&tid1, NULL, ThreadEntry, NULL);
	pthread_create(&tid1, NULL, ThreadEntry, NULL);


	pthread_join(tid1, NULL);
	pthread_join(tid2, NULL);

	pthread_cond_destory(&cond, NULL);//互斥锁初始化函数
	pthread_mutex_destory(&mutex);//同步释放函数

	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值