运用条件变量保持线程同步
来源:互联网 发布:人力资源软件有哪些 编辑:程序博客网 时间:2024/05/16 07:09
线程同步手段:互斥锁,读写锁,条件变量。
本文实例利用条件变量保持读写同步
#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <string.h>//#define THREAD_SYNC_PROTECTstruct msg { struct msg *m_next; char context[100];};struct msg *workq = NULL;int flag = 1;pthread_cond_t qready = PTHREAD_COND_INITIALIZER;pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;void process_msg(void){ struct msg *mp = NULL; for (;;) {#if defined THREAD_SYNC_PROTECT /* protect condition varialbe without missing any condition change */ pthread_mutex_lock(&qlock); while (workq == NULL) { /* append thread to wait queue and make thread sleep, finally unlock mutex */ pthread_cond_wait(&qready, &qlock); /* relock mutex when function "pthread_cond_wait" returns */ printf("condition match!\n"); }#endif if (workq != NULL) { mp = workq; workq = mp->m_next; }#if defined THREAD_SYNC_PROTECT pthread_mutex_unlock(&qlock);#endif if (workq != NULL) { /* process message */ printf("thread %u :receive message %s\n", pthread_self(), mp->context); free(mp); } }}void enqueue_msg(struct msg *mp){ /* Get right to operate queue */ pthread_mutex_lock(&qlock); mp->m_next = workq; workq = mp; pthread_mutex_unlock(&qlock); pthread_cond_signal(&qready);}void send_msg(void){ int i; for (i = 0; i < 10; i++) { struct msg *mp = malloc(sizeof(struct msg)); if (NULL == mp) { printf("malloc failed!\n"); break; } sprintf(mp->context, "%s[%d] request", "customer", i); enqueue_msg(mp); sleep(1); } flag = 0;}int main(void){ pthread_t tid_send, tid_process1, tid_process2; int ret ; pthread_mutex_init(&qlock, NULL); ret = pthread_create(&tid_process2, NULL, process_msg, NULL); if (ret != 0) { printf("create pthread send_msg failed!\n"); return -1; } ret = pthread_create(&tid_process1, NULL, process_msg, NULL); if (ret != 0) { printf("create pthread send_msg failed!\n"); return -1; } ret = pthread_create(&tid_send, NULL, send_msg, NULL); if (ret != 0) { printf("create pthread send_msg failed!\n"); return -1; } while(flag); return 0;}
- 运用条件变量保持线程同步
- Python使用条件变量保持线程同步
- 线程同步-条件变量
- 线程同步条件变量
- 线程同步---条件变量
- 线程同步条件变量
- 线程同步-----条件变量
- 线程同步-条件变量
- Linux 线程同步---条件变量
- 线程同步 之 条件变量
- Linux 线程同步---条件变量
- Linux 线程同步---条件变量
- Linux 线程同步---条件变量
- Linux 线程同步---条件变量
- Linux 线程同步---条件变量
- Linux 线程同步---条件变量
- 线程的同步--条件变量
- Linux 线程同步---条件变量
- Cocoss2d-x开发流程工具化思想与实现
- CodeForces Round 218 D. Vessels(学姐我没用线段树系列)
- 写出当前数据库中的所有用户表
- Android4.2 G-Sensor工作流程
- MySQL中正则表达式的简单用法
- 运用条件变量保持线程同步
- mybatis学习笔记(二) 多pojo,复杂映射
- apache的ssl使用方法
- C语言 - ACM题目:软件版本问题
- 项目中的一些学习
- SEH异常综合使用 (6)
- spring配置文件ApplicationContext.xml文件里面没有提示功能
- 做一名“数据科学家”,规划您未来5至10年的职业发展
- 混迹于C++之拷贝赋值函数和拷贝构造函数(二)