同步
同步控制着线程和线程之间的执行顺序。(主要是抢占式执行惹的祸,有的时候需要线程和线程之间按照一定的顺序来执行)。
相关函数:
位置在主函数中:
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 必须是原子的,因为要避免其他线程的通知消息没收到,傻等,所以他俩不可拆分的。而这个不分开的操作就是缘子操作。
代码示例:
#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; }