Unix IPC之互斥锁与条件变量
互斥锁
1、函数声明
#include <pthread.h> /* Mutex handling. */ /* Initialize a mutex. */
extern int pthread_mutex_init (pthread_mutex_t *__mutex,
__const pthread_mutexattr_t *__mutexattr)
__THROW __nonnull (()); /* Destroy a mutex. */
extern int pthread_mutex_destroy (pthread_mutex_t *__mutex)
__THROW __nonnull (()); /* Try locking a mutex. */
extern int pthread_mutex_trylock (pthread_mutex_t *__mutex)
__THROW __nonnull (()); /* Lock a mutex. */
extern int pthread_mutex_lock (pthread_mutex_t *__mutex)
__THROW __nonnull (());
/* Unlock a mutex. */
extern int pthread_mutex_unlock (pthread_mutex_t *__mutex)
__THROW __nonnull (());
2、函数使用
pthread_mutex_lock(mutex);
// 临界区
// do something....
// 临界区
pthread_mutex_unlock(mutex); /**
* 如果尝试给一个已由另外某个线程锁住的互斥锁上锁
* pthread_mutex_lock将阻塞,直到该互斥锁解锁为止
* pthread_mutex_trylock是对应的非阻塞函数,若互斥锁已锁住,则立即返回一个EBUSY错误
*/
3、测试用例:
/* include main */
#include "unpipc.h" #define MAXNITEMS 1000000
#define MAXNTHREADS 100 int nitems; /* read-only by producer and consumer */
struct
{
pthread_mutex_t mutex;
int buff[MAXNITEMS];
int nput; // 记录已写条目数目
int nval;
} shared = { PTHREAD_MUTEX_INITIALIZER }; void *produce(void *);
void *consume(void *); int main(int argc, char **argv)
{
int i, nthreads, count[MAXNTHREADS];
pthread_t tid_produce[MAXNTHREADS]; // 多生产者线程
pthread_t tid_consume; // 单消费者线程 if (argc != )
err_quit("usage: prodcons2 <#items> <#threads>");
nitems = min(atoi(argv[]), MAXNITEMS);
nthreads = min(atoi(argv[]), MAXNTHREADS); /* 最好调用pthread_setconcurrency函数 */
Set_concurrency(nthreads); // 设置并行级别,大部分系统中该函数并没有什么作用
/* 4start all the producer threads */
for (i = ; i < nthreads; i++)
{
count[i] = ;
Pthread_create(&tid_produce[i], NULL, produce, &count[i]);
} /* 4wait for all the producer threads */
for (i = ; i < nthreads; i++)
{
Pthread_join(tid_produce[i], NULL);
printf("count[%d] = %d\n", i, count[i]);
} /* 4start, then wait for the consumer thread */
Pthread_create(&tid_consume, NULL, consume, NULL);
Pthread_join(tid_consume, NULL); exit();
}
/* end main */ /* include producer */
void *produce(void *arg)
{
for ( ; ; )
{
Pthread_mutex_lock(&shared.mutex);
if (shared.nput >= nitems)
{
Pthread_mutex_unlock(&shared.mutex);
return(NULL); /* array is full, we're done */
}
shared.buff[shared.nput] = shared.nval;
shared.nput++;
shared.nval++;
Pthread_mutex_unlock(&shared.mutex);
*((int *) arg) += ; // 每个线程修改各自的元素
}
} void *consume(void *arg)
{
int i; for (i = ; i < nitems; i++)
{
if (shared.buff[i] != i)
printf("buff[%d] = %d\n", i, shared.buff[i]);
}
return(NULL);
}
/* end producer */
条件变量
互斥锁用于上锁,条件变量用于等待,这是两种不同类型的同步。
1、函数声明
#include <pthread.h> /* Wake up one thread waiting for condition variable COND. */
extern int pthread_cond_signal (pthread_cond_t *__cond)
__THROW __nonnull (()); /* Wake up all threads waiting for condition variables COND. */
extern int pthread_cond_broadcast (pthread_cond_t *__cond)
__THROW __nonnull (()); /* Wait for condition variable COND to be signaled or broadcast.
MUTEX is assumed to be locked before. This function is a cancellation point and therefore not marked with
__THROW. */
extern int pthread_cond_wait (pthread_cond_t *__restrict __cond,
pthread_mutex_t *__restrict __mutex)
__nonnull ((, )); /* Wait for condition variable COND to be signaled or broadcast until
ABSTIME. MUTEX is assumed to be locked before. ABSTIME is an
absolute time specification; zero is the beginning of the epoch
(00:00:00 GMT, January 1, 1970). This function is a cancellation point and therefore not marked with
__THROW. */
extern int pthread_cond_timedwait (pthread_cond_t *__restrict __cond,
pthread_mutex_t *__restrict __mutex,
__const struct timespec *__restrict
__abstime) __nonnull ((, , ));
2、函数使用
struct
{
pthread_mutex_t mutex;
pthread_cond_t cond;
// ...
} var = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER }; /**
* 给条件变量发送信号代码
*/
Pthread_mutex_lock(&var.mutex);
if(condition0 == true)
{
Pthread_cond_signal(&var.cond);
}
// do something...
pthread_mutex_unlock(&var.mutex); /**
* 测试条件变量
*/
Pthread_mutex_lock(&var.mutex);
while(condition1 == false) // 防止接收到错误信号
{
Pthread_cond_wait(&var.cond, &var.mutex);
}
// do something...
pthread_mutex_unlock(&var.mutex);
关于Pthread_cond_wait(&var.cond, &var.mutex)函数的说明
The mutex passed to pthread_cond_wait protects the condition.The caller passes it locked to the function, which then atomically places them calling thread on the list of threads waiting for the condition and unlocks the mutex. This closes the window between the time that the condition is checked and the time that the thread goes to sleep waiting for the condition to change, so that the thread doesn't miss a change in the condition. When pthread_cond_wait returns, the mutex is again locked.
// 函数执行期间锁的调用(伪码)
lock(mutex) ----------------a.lock pthread_cond_wait()
{
unlock(mutex)-------------a.unlock
if (条件不满足)
suspend();
else
{
lock(mutex)-------------b.lock
return
}
} dosomething(); unlock(mutex);---------------b.unlock
3、测试用例
/* include globals */
#include "unpipc.h" #define MAXNITEMS 1000000
#define MAXNTHREADS 100 /* globals shared by threads */
int nitems; /* read-only by producer and consumer */
int buff[MAXNITEMS];
struct
{
pthread_mutex_t mutex;
int nput; /* next index to store */
int nval; /* next value to store */
} put = { PTHREAD_MUTEX_INITIALIZER }; struct
{
pthread_mutex_t mutex;
pthread_cond_t cond;
int nready; /* number ready for consumer */
} nready = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER };
/* end globals */ void *produce(void *);
void *consume(void *); /* include main */
int
main(int argc, char **argv)
{
int i, nthreads, count[MAXNTHREADS];
pthread_t tid_produce[MAXNTHREADS], tid_consume; if (argc != )
err_quit("usage: prodcons6 <#items> <#threads>");
nitems = min(atoi(argv[]), MAXNITEMS);
nthreads = min(atoi(argv[]), MAXNTHREADS); Set_concurrency(nthreads + );
/* 4create all producers and one consumer */
for (i = ; i < nthreads; i++)
{
count[i] = ;
Pthread_create(&tid_produce[i], NULL, produce, &count[i]);
}
Pthread_create(&tid_consume, NULL, consume, NULL); /* wait for all producers and the consumer */
for (i = ; i < nthreads; i++)
{
Pthread_join(tid_produce[i], NULL);
printf("count[%d] = %d\n", i, count[i]);
}
Pthread_join(tid_consume, NULL); exit();
}
/* end main */ /* include prodcons */
void *
produce(void *arg)
{
for ( ; ; )
{
Pthread_mutex_lock(&put.mutex);
if (put.nput >= nitems)
{
Pthread_mutex_unlock(&put.mutex);
return(NULL); /* array is full, we're done */
}
buff[put.nput] = put.nval;
put.nput++;
put.nval++;
Pthread_mutex_unlock(&put.mutex); /* 同步生产者与消费者线程 */
Pthread_mutex_lock(&nready.mutex);
if (nready.nready == )
{
// 发送信号,系统调用等待在nready.cond上的线程
// 该线程开始运行,但是立即停止,因为无法获取nready.mutex锁
Pthread_cond_signal(&nready.cond);
} nready.nready++;
Pthread_mutex_unlock(&nready.mutex); *((int *) arg) += ;
}
} void *
consume(void *arg)
{
int i; for (i = ; i < nitems; i++)
{
Pthread_mutex_lock(&nready.mutex);
while (nready.nready == ) // 当产品数目为0时才会有线程阻塞,此时采用必要发送条件信号
{
Pthread_cond_wait(&nready.cond, &nready.mutex);
} nready.nready--;
Pthread_mutex_unlock(&nready.mutex); if (buff[i] != i)
printf("buff[%d] = %d\n", i, buff[i]);
}
return(NULL);
}
/* end prodcons */
Unix IPC之互斥锁与条件变量的更多相关文章
- node源码详解(七) —— 文件异步io、线程池【互斥锁、条件变量、管道、事件对象】
本作品采用知识共享署名 4.0 国际许可协议进行许可.转载保留声明头部与原文链接https://luzeshu.com/blog/nodesource7 本博客同步在https://cnodejs.o ...
- 进程间通信机制(管道、信号、共享内存/信号量/消息队列)、线程间通信机制(互斥锁、条件变量、posix匿名信号量)
注:本分类下文章大多整理自<深入分析linux内核源代码>一书,另有参考其他一些资料如<linux内核完全剖析>.<linux c 编程一站式学习>等,只是为了更好 ...
- linux c 线程间同步(通信)的几种方法--互斥锁,条件变量,信号量,读写锁
Linux下提供了多种方式来处理线程同步,最常用的是互斥锁.条件变量.信号量和读写锁. 下面是思维导图: 一.互斥锁(mutex) 锁机制是同一时刻只允许一个线程执行一个关键部分的代码. 1 . ...
- 非常精简的Linux线程池实现(一)——使用互斥锁和条件变量
线程池的含义跟它的名字一样,就是一个由许多线程组成的池子. 有了线程池,在程序中使用多线程变得简单.我们不用再自己去操心线程的创建.撤销.管理问题,有什么要消耗大量CPU时间的任务通通直接扔到线程池里 ...
- linux 线程的同步 二 (互斥锁和条件变量)
互斥锁和条件变量 为了允许在线程或进程之间共享数据,同步时必须的,互斥锁和条件变量是同步的基本组成部分. 1.互斥锁 互斥锁是用来保护临界区资源,实际上保护的是临界区中被操纵的数据,互斥锁通常用于保护 ...
- Linux互斥锁、条件变量和信号量
Linux互斥锁.条件变量和信号量 来自http://kongweile.iteye.com/blog/1155490 http://www.cnblogs.com/qingxia/archive/ ...
- 互斥锁和条件变量(pthread)相关函数
互斥锁 #include <pthread.h> // 若成功返回0,出错返回正的Exxx值 // mptr通常被初始化为PTHREAD_MUTEX_INITIALIZER int pth ...
- linux 互斥锁和条件变量
为什么有条件变量? 请参看一个线程等待某种事件发生 注意:本文是linux c版本的条件变量和互斥锁(mutex),不是C++的. mutex : mutual exclusion(相互排斥) 1,互 ...
- 线程私有数据TSD——一键多值技术,线程同步中的互斥锁和条件变量
一:线程私有数据: 线程是轻量级进程,进程在fork()之后,子进程不继承父进程的锁和警告,别的基本上都会继承,而vfork()与fork()不同的地方在于vfork()之后的进程会共享父进程的地址空 ...
随机推荐
- CJOJ 2482 【POI2000】促销活动(STL优先队列,大根堆,小根堆)
CJOJ 2482 [POI2000]促销活动(STL优先队列,大根堆,小根堆) Description 促销活动遵守以下规则: 一个消费者 -- 想参加促销活动的消费者,在账单下记下他自己所付的费用 ...
- 字符串连接比较(std::unique_ptr实现)
比较代码之间可能相差大,可是速度相差很大,而且目的在于测试unique_ptr使用...; C/C++: #include <iostream> std::unique_ptr<ch ...
- mysql8 net start mysql 服务名无效
解决办法: 1.win+R打开运行窗口,输入services.msc 2.在其中查看mysql的服务名,我的是MySQL80 3.以管理员身份打开cmd,输入net start MySQL80 出现下 ...
- linux命令总结dd命令详解
一:dd命令 dd:用指定大小的块拷贝一个文件,并在拷贝的同时进行指定的转换. 注意:指定数字的地方若以下列字符结尾,则乘以相应的数字:b=512:c=1:k=1024:w=2 参数注释: if=文件 ...
- CoreDNS配置kubernetes作为后端
概述 coredns之所以如此名声大噪,就是因为从kubernetes1.9开始引入,作为kubernetes内部服务发现的默认dns.毫无疑问kubernetes是coredns的后端之一,所以我们 ...
- 安装lsb_release
lsb_release命令用来查看当前系统的发行版信息(prints certain LSB (Linux Standard Base) and Distribution information.). ...
- Eclipse中遇到main方法不能运行 的情况
java.lang.UnsupportedClassVersionError: Bad version number in .class file 造成这种过错是ni的支撑Tomcat运行的JDK版本 ...
- bzoj千题计划135:bzoj1066: [SCOI2007]蜥蜴
http://www.lydsy.com/JudgeOnline/problem.php?id=1066 每个柱子拆成两个点 i<<1,i<<1|1,之间连流量为高度的边 如果 ...
- Git之代码合并及分支管理
环境说明: 对于一个git项目而言,公司在gitlab上有对应的三个分支,以kazihuo项目为例说明,分别是development.master.testing,运维首先在gitlab上创建一个gr ...
- ZeroMQ API(二) 上下文
1.创建上下文 1.1 zmq_ctx_new(3) 1.1.1 名称 zmq_ctx_new - 创建新的ZMQ上下文 1.1.2 概要 void * zmq_ctx_new(); 1.1.3 描述 ...