互斥锁与条件变量应用
来源:互联网 发布:sql注入漏洞如何处理 编辑:程序博客网 时间:2024/05/01 21:29
一个经典的条件变量与互斥锁的应用。程序如下:
#include<pthread.h>#include<stdio.h>#include<stdlib.h>pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;pthread_cond_t cond = PTHREAD_COND_INITIALIZER;struct node{ int number; struct node *next;} *head = NULL;void *thread (void *arg){ struct node *p; while (1) { pthread_mutex_lock (&mutex); while (head == NULL) pthread_cond_wait (&cond, &mutex); p = head; head = head->next; printf ("Got %d from front of queue\n", p->number); free (p); pthread_mutex_unlock (&mutex); } return NULL;}int main (int argc, char *argv[]){ pthread_t tid; int i; struct node *p; pthread_create (&tid, NULL, thread, NULL); for (i = 0; i < 10; i++) { p = malloc (sizeof (struct node)); pthread_mutex_lock (&mutex); p->number = i; p->next = head; head = p; pthread_cond_signal (&cond); pthread_mutex_unlock (&mutex); sleep (1); } pthread_cancel (tid); int result; pthread_join (tid,NULL); printf ("done,exit"); return 0;}
刚开对此程序不太理解,经过查阅资料终于搞清楚了一些细节问题
1.条件变量必须和互斥锁一起使用,应为条件变量是全局变量,需要防止多个线程同时对条件变量wait操作。
2.pthread_cond_wait()函数内部包含一对解锁和加锁操作:在进入pthread_cond_wait()前,调用线程已经加锁;
进入pthread_cond_wait()后,线程加入条件变量等待队列,此时解开互斥锁。当等待条件被满足时,线程退出
pthread_cond_wait(),同时尝试对互斥锁加锁来访问临界区变量。
3.pthread_cond_signal在多处理器上可能同时唤醒多个线程,当你只能让一个线程处理某个任务时,其它被唤
的线程就需要继续挂起等待,故使用循环测试(如上例的while (head == NULL))。
4.pthread_cancel (tid)的作用是向线程tid发送退出请求,线程会继续运行至取消点退出,该例的取消点是
pthread_cond_wait(),若注释掉该句,则子线程会一直在pthread_cond_wait()中等待,程序结束不了。
0 0
- 互斥锁与条件变量应用
- 条件变量与互斥锁
- 互斥锁与条件变量
- 互斥锁与条件变量
- 条件变量与互斥锁
- 互斥锁与条件变量
- 互斥锁与条件变量
- 条件变量与互斥锁
- 互斥锁与条件变量
- linux 条件变量与互斥锁
- 条件变量与互斥锁解析
- 线程互斥锁和条件变量应用
- linux 多线程编程 互斥锁与条件变量
- 互斥锁与条件变量配合使用
- 互斥锁与条件变量的通俗语义
- 同步(一)互斥锁与条件变量
- 条件变量与互斥锁、信号量的区别
- Linux多线程 互斥锁与条件变量使用
- 【小游戏】有意思的小游戏集合
- linux sudoers设置
- JAVA事件适配器的作用
- 对象作为数据成员
- 运用Handler与线程的sleep(long)的安卓定时器
- 互斥锁与条件变量应用
- 来自官网update的一些代码
- 读书笔记-《拆掉思维里的墙》
- VB.NET版机房收费系统—数据库设计
- 锁 阅读文献篇
- 使用Setup API枚举系统设备
- 静态成员
- Highcharts结合Ajax完美实现时序图的展现(asp.net)版本(我是拿来做参考的)
- 一款基于Webgl实现的3D类网页游戏