[Linux]多线程同步之pthread_cond_wait()学习笔记
来源:互联网 发布:windows ad域博客 编辑:程序博客网 时间:2024/05/23 19:10
线程间同步的一种情况:线程A需要等某个条件成立才能继续往下执行,现在这个条件不成立,线程A就阻塞等待,而线程B在执行过程中使这个条件成立了,就唤醒线程A继续执行。
在pthread库中通过条件变量(Condition Variable)来阻塞等待一个条件,或者唤醒等待这个条件的线程 。
一个生产者-消费者的例子:消费者A等待生产者B产出产品后才打印,否则消费者阻塞等待生产者生产。
#include <stdlib.h>#include <pthread.h>#include <stdio.h>#include <unistd.h>struct msg { struct msg *next; int num;};struct msg *head;pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;void *producer(void *p){ struct msg *mp; while(1){ mp = malloc(sizeof(struct msg)); mp->num = rand() % 1000 + 1; printf("produce %d\n", mp->num); pthread_mutex_lock(&lock); mp->next = head; head = mp; pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(2); }}void *consumer(void *p){ while(1){ pthread_cond_wait(&has_product, &lock); struct msg *tmp = head; while(tmp != NULL) { printf("%d ", tmp->num); tmp = tmp->next; } printf("\n"); }}int main(){ pthread_t pid, cid; pthread_create(&pid, NULL, producer, NULL); pthread_create(&cid, NULL, consumer, NULL); pthread_join(pid, NULL); pthread_join(cid, NULL); return 0;}
运行结果:
0 0
- [Linux]多线程同步之pthread_cond_wait()学习笔记
- [Linux]多线程同步之sem_wait()学习笔记
- Linux下pthread_cond_wait()多线程同步实例
- pthread_cond_wait多线程同步
- linux多线程学习笔记三---线程同步之信号量
- linux多线程函数pthread_cond_wait
- 多线程编程之pthread_cond_wait
- linux学习之十六---条件变量pthread_cond_wait
- java 多线程学习笔记之 线程同步
- linux多线程 pthread_cond_wait() 函数
- linux多线程之同步
- linux多线程学习笔记四---线程同步之互斥锁、读写锁和条件变量
- Linux程序设计学习笔记----多线程编程线程同步机制之互斥量(锁)与读写锁
- Linux程序设计学习笔记----多线程编程之线程同步条件变量
- 学习笔记之Linux内核同步方法
- 多线程开发学习笔记之线程同步——互斥量
- 多线程开发学习笔记之线程同步——信号量
- 多线程开发学习笔记之线程同步——事件
- JAVA 之 java概述
- 微信公众号开发:PHP,对接微信公众账号的测试文档wx_sample.php的解析
- 第九周项目4--广义表算法库及应用1
- 数据库基础知识2
- spark与hadoop对比
- [Linux]多线程同步之pthread_cond_wait()学习笔记
- c语言基本数据类型
- 第九周项目4--广义表算法库及应用2
- 第十周项目1--二叉树算法库
- odroid x2安装ubuntu系统,HDMI显示,说说折腾事儿。
- JSP中的JavaBean和动作元素(四)
- 百度地图 公交查询 redis入门
- NodeJS+express+ajax的简单post登录应用
- socket 套接字编程