进程通信学习笔记(互斥锁和条件变量)
来源:互联网 发布:台达dvp14ss编程软件 编辑:程序博客网 时间:2024/06/06 17:18
1、互斥锁:上锁和解锁
Posix互斥锁作为数据类型pthread_mutex_t的变量声明。如果互斥锁变量是静态分配的,那么可以把它初始化成常值PTHREAD_MUTEX_INITIALIZER。如果互斥锁是动态分配的(调用malloc)或者分配在共享内存中,必须在运行时刻调用pthread_mutex_init函数来初始化它
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t *mptr);
int pthread_mutex_trylock(pthread_mutex_t *mptr);
int pthread_mutex_unlock(pthread_mutex_t *mptr);
成功返回0,失败返回为正的Exxx值
2、条件变量:等待与信号发送
互斥锁用于上锁,条件变量用于等待。这两种不同类型的同步都是需要的
条件变量是类型pthread_cond_t的变量
#include <pthread.h>
int pthread_cond_wait(pthread_cond_t *cptr, pthread_mutex_t *mptr);
int pthread_cond_signal(pthread_cond_t *cptr);
成功返回0,出错返回正的Exxx值
pthread_cond_wait该函数原子地执行以下两个动作
(1)给互斥锁解锁
(2)把调用线程投入睡眠,直到另外某个线程就本条件变量调用pthread_cond_signal
pthread_cond_wait在返回前重新给互斥锁上锁
3、条件变量:定时等待和广播
pthread_cond_signal只唤醒在相应条件变量上的一个线。某些情况下一个线程认定有多个其他线程应被唤醒,可调用pthread_cond_broadcast唤醒阻塞在相应条件变量上的所有线程
#include <pthread.h>
int pthread_cond_broadcast(pthread_cond_t *cptr);
int pthread_cond_timedwait(pthread_cond_t *cptr, pthread_mutex_t *mptr, const struct timespec *abstime);
成功返回0,失败返回正的Exxx值
4、互斥锁和条件变量的属性
其初始化和摧毁用以下函数
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *mptr, const pthread_mutexattr_t *attr);
int pthread_mutex_destroy(pthread_mutex_t *mptr);
int pthread_cond_init(pthread_cond_t *cptr, const pthread_condattr_t *attr);
int pthread_cond_destroy(pthread_cond_t *cptr);
互斥锁属性和条件变量属性初始化和摧毁
int pthread_mutexattr_init(pthread_mutexattr_t *attr);
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
int pthread_condattr_init(pthread_condattr_t *attr);
int pthread_condattr_destroy(pthread_condattr_t *attr);
使能或禁止特定的属性通过以下函数来完成,如指定互斥锁或条件变量在不同进程间共享,而不是在单个进程内的不同线程间共享
int pthread_mutexattr_getpshared(const pthread_mutexattr_t *attr, int *valptr);
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int value);
int pthread_condattr_getpshared(const pthread_condattr_t *attr, int *valptr);
int pthread_condattr_setpshared(pthread_condattr_t *attr, int value);
- 进程通信学习笔记(互斥锁和条件变量)
- 进程间通信笔记(5)—互斥锁和条件变量
- Linux进程通信[2]-互斥锁和条件变量
- IPC通信:互斥锁和条件变量
- IPC通信:互斥锁和条件变量
- IPC通信:互斥锁和条件变量
- 深入理解Linux进程间通信(IPC)-- 互斥锁和条件变量
- 笔记:进程间通信——同步(互斥锁、读写锁、条件变量、信号量)以及Linux中的RCU
- 【学习笔记】SVM算法-松弛变量和最优化条件
- muduo网络库学习笔记(4):互斥量和条件变量
- linux多线程学习笔记四---线程同步之互斥锁、读写锁和条件变量
- 进程间的通信(互斥锁、条件变量、读写锁、文件锁、信号灯)
- 进程间的通信(互斥锁、条件变量、读写锁、文件锁、信号灯)
- 【转】 进程间的通信(互斥锁、条件变量、读写锁、文件锁、信号灯)
- 进程间的通信(互斥锁、条件变量、读写锁、文件锁、信号灯)
- 进程间的通信(互斥锁、条件变量、读写锁、文件锁、信号灯)
- 进程间的通信(互斥锁、条件变量、读写锁、文件锁、信号灯)
- 进程间的通信(互斥锁、条件变量、读写锁、文件锁、信号灯)
- maven常见问题问答
- SVM推导过程及SMO详细求解过程(二)
- 哈夫曼编码(HDU 1053)
- Android 对话框(Dialog)大全 建立你自己的对话框
- 浅谈C++中变量的底层实现机制
- 进程通信学习笔记(互斥锁和条件变量)
- UVa - 414 - Machined Surfaces(AC)
- 初识Extjs4.2-hello world
- 用C语言实现myshell
- CSS的三种选择器
- R语言layout函数学习笔记
- Qt中文字体改变大小
- 一张.NET 2015的图
- Vmware虚拟机的网络连接的桥接模式