#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string>
pthread_cond_t cond1;
pthread_cond_t cond2;
pthread_mutex_t block1;
pthread_mutex_t block2;
pthread_mutex_t numBlock = PTHREAD_MUTEX_INITIALIZER;
int num = 0;
void *display(void *para) {
int i = 0;
while (1) {
pthread_cond_wait(&cond1, &block1);
pthread_mutex_lock(&numBlock);
num++;
pthread_mutex_unlock(&numBlock);
sleep(1);
printf("display num==[%d]\n", num);
pthread_cond_signal(&cond2);
}
}
int main(int argc, char const *argv[]) {
pthread_t id;
pthread_cond_init(&cond1, NULL);
pthread_cond_init(&cond2, NULL);
pthread_create(&id, NULL, display, NULL);
while (1) {
pthread_mutex_lock(&numBlock);
num++;
pthread_mutex_unlock(&numBlock);
sleep(1);
printf("main num+++[%d]\n", num);
pthread_cond_signal(&cond1);
pthread_cond_wait(&cond2,&block2);
}
pthread_join(id, NULL);
return 0;
}
linux c++ 多线程同步
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- From : https://blog.csdn.net/qq_39382769/article/details/...
- 创建和结束线程 包括 pthread_create:用于创建一个线程 pthread_exit:线程函数结束时调用...
- 线程属性 pthread_attr_t 结构体定义了一套完整的线程属性: 可以看到,各种线程属性都包含在一个字符数...
- 通常而言,同步变量和条件变量声明为全局,所以,多个线程可以访问它们。虽然这需要使用同步变量的所有线程提供了方便,但...
- 1. 竞争条件 当两个或更多线程或进程试图同时修改同一个共享、可修改数据块时,这种情况称做竞争条件或数据竞争(da...