【Linux】Mutex互斥量线程同步的例子
0、互斥量
Windows下的互斥量
是个内核对象,每次WaitForSingleObject和ReleaseMutex时都会检查当前线程ID和占有互斥量的线程ID是否一致。
当多次Wait**时就要对应多次ReleaseMutex, 当ReleaseMutex过多次数时如果发现当前占有互斥量的线程ID和当前调用ReleaseMutex的线程ID不一致时仅仅返回FLASE,GetLastError返回ERROR_NOT_OWNER,没有其他副作用。
当占有mutex的线程在Release之前退出时,该mutex被【遗弃】,此时系统自动收回mutex,可供其他线程申请。
允许多次等待
WaitForSingleObject(hMutex, time);
WaitForSingleObject(hMutex, itme);
多次等待 对应多次释放
ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
Linux下的互斥量
可以设置互斥量的属性是否为可以被同一个线程多次lock, 还可以设置该互斥量的范围,即是用于进程之间同步 还是 同一进程不同线程之间的同步。
相关API 将说明见代码注释部分。
1、相关API
//Initialize a mutex with attribute(can be NULL)
int pthread_mutex_init(
pthread_mutex_t* mutex,
const pthread_mutexattr_t* mutexattr); //lock a mutex
int pthread_mutex_lock(pthread_mutex_t* mutex); //ulock a mutex
int pthread_mutex_unlock(pthread_mutex_t* mutex); //destroy a mutex
int pthread_mutex_destroy(pthread_mutex_t* mutex); int pthread_mutexattr_setpshared(
pthread_mutexattr_t* mattr,
int pshared //PTHREAD_PROCESS_SHARE | PTHREAD_PROCESS_PRIVATE
); int pthread_mutexattr_getshared(
pthread_mutexattr_t* mattr,
int* pshared); int pthread_mutexattr_settype(
pthread_mutexattr_t* attr,
int type //PTHREAD_MUTEX_TIMED_NP -- default value
//PTHREAD_MUTEX_RECURISIVE_NP -- allow a thread lock multitimes
//PTHREAD_MUTEX_ERRORCHECK_NO -- check error lock, return EDEADLK if the same thread want to LOCK
//PTHREAD_MUTEX_ADAPTIVE_NO -- adaptive lock, the simplest lock
) int pthread_mutexattr_gettype(
pthread_mutexattr_t* attr,
int* type
)
2、demo
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <errno.h> using namespace std; /***********************************************
*
* Initialize a mutex with attribute(can be NULL)
* int pthread_mutex_init(
* pthread_mutex_t* mutex,
* const pthread_mutexattr_t* mutexattr);
*
* lock a mutex
* int pthread_mutex_lock(pthread_mutex_t* mutex);
*
* unlock a mutex
* int pthread_mutex_unlock(pthread_mutex_t* mutex);
*
* destroy a mutex
* int pthread_mutex_destroy(pthread_mutex_t* mutex);
*
* int pthread_mutexattr_setpshared(
* pthread_mutexattr_t* mattr,
* int pshared //PTHREAD_PROCESS_SHARE | PTHREAD_PROCESS_PRIVATE
* );
*
* int pthread_mutexattr_getshared(
* pthread_mutexattr_t* mattr,
* int* pshared);
*
* int pthread_mutexattr_settype(
* pthread_mutexattr_t* attr,
* int type //PTHREAD_MUTEX_TIMED_NP -- default value
* //PTHREAD_MUTEX_RECURISIVE_NP -- allow a thread lock multitimes
* //PTHREAD_MUTEX_ERRORCHECK_NO -- check error lock, return EDEADLK if the same thread want to LOCK
* //PTHREAD_MUTEX_ADAPTIVE_NO -- adaptive lock, the simplest lock
* )
*
*
* int pthread_mutexattr_gettype(
* pthread_mutexattr_t* attr,
* int* type
* )
* *********************************************/ void* work_thread(void* p)
{
if (NULL == p)
return const_cast<char*>("invalid thread argument"); pthread_mutex_t* pMutex = (pthread_mutex_t*)(p); //current thread ID
pthread_t nThreadID = pthread_self(); int i = ;
while(++ i <= )
{
//lock multi times
pthread_mutex_lock(pMutex);
pthread_mutex_lock(pMutex); cout << "Thread " << nThreadID << " is Running! " << endl; //and so unlock multi times
pthread_mutex_unlock(pMutex);
pthread_mutex_unlock(pMutex);
usleep( * ); //1 miliseconds
} return const_cast<char*>("------ finish -----------"); } void* work_thread2(void* p)
{
if (NULL == p)
return const_cast<char*>("invalid thread argument"); pthread_mutex_t* pMutex = (pthread_mutex_t*)(p); //current thread ID
pthread_t nThreadID = pthread_self(); int i = ;
while(++ i <= )
{
//if current thread can not enter mutex,
//and the function pthread_mutex_trylock will RETURN Immediatly
if ( EBUSY == pthread_mutex_trylock(pMutex))
cout << "Other thread is lock the resouce, i am waiting.." << endl;
else
{
cout << "Thread " << nThreadID << " is Running! " << endl;
pthread_mutex_unlock(pMutex);
usleep( * ); //1 miliseconds
} }
return const_cast<char*>("------ finish -----------"); } int main()
{
const size_t nThreadCount = ;
pthread_t threadIDs[nThreadCount];
int nRet = -;
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
void* pRet = NULL; //thread return value //allow a thread lock multi times
nRet = pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP); nRet = pthread_mutex_init(&mutex, &mutexattr);
if ( != nRet)
return -; for (size_t i = ; i < nThreadCount - ; ++ i)
{
nRet = pthread_create(&threadIDs[i], NULL, work_thread, (void*)(&mutex));
if ( != nRet)
continue;
} nRet = pthread_create(&threadIDs[nThreadCount - ], NULL, work_thread2, (void*)(&mutex));
if ( != nRet)
cerr << endl << "work_thread2 created falied! " << endl; for (size_t i = ; i < nThreadCount; ++ i)
{
nRet = pthread_join(threadIDs[i], &pRet);
if ( == nRet)
{
cout << " Thread " << threadIDs[i] << " Finished ! " \
" It's return value is " << (char*)pRet << endl;
} } pthread_mutex_destroy(&mutex); return ;
}
3、执行结果

【Linux】Mutex互斥量线程同步的例子的更多相关文章
- 【Linux】Semaphore信号量线程同步的例子
0. 信号量 Linux下的信号量和windows下的信号量稍有不同. Windows Windows下的信号量有一个最大值和一个初始值,初始值和最大值可以不同. 而且Windows下的信号量是一个 ...
- Linux并发与同步专题 (4) Mutex互斥量
关键词:mutex.MCS.OSQ. <Linux并发与同步专题 (1)原子操作和内存屏障> <Linux并发与同步专题 (2)spinlock> <Linux并发与同步 ...
- c# Thread5——线程同步之基本原子操作。Mutex互斥量的使用
之前的博文也说到了如果多线程对于访问的公共资源操作都是原子操作,那么可以避免竞争条件.关于多线程的竞争可以百度. 1.执行最基本的原子操作 c#提供了一系列供我们使用的原子操作的方法和类型,比如我们的 ...
- linux系统编程:线程同步-相互排斥量(mutex)
线程同步-相互排斥量(mutex) 线程同步 多个线程同一时候訪问共享数据时可能会冲突,于是须要实现线程同步. 一个线程冲突的演示样例 #include <stdio.h> #includ ...
- C++多线程同步之Mutex(互斥量)
原文链接: http://blog.csdn.net/olansefengye1/article/details/53086141 一.互斥量Mutex同步多线程 1.Win32平台 相关函数和头文件 ...
- Linux 多线程互斥量互斥
同步 同一个进程中的多个线程共享所在进程的内存资源,当多个线程在同一时刻同时访问同一种共享资源时,需要相互协调,以避免出现数据的不一致和覆盖等问题,线程之间的协调和通信的就叫做线程的同步问题, 线程同 ...
- Linux学习笔记21——线程同步的两种方式
一 用信号量同步 1 信号量函数的名字都以sem_开头,线程中使用的基本信号量函数有4个 2 创建信号量 #include<semaphore.h> int sem_init(sem_t ...
- linux学习笔记之线程同步机制
一.基础知识. 1:线程同步机制:互斥量,读写锁,条件变量,自旋锁,屏障. 1,互斥量:每个进程访问被互斥量保护的资源时,都需要先对互斥量进行判断. 1)互斥量重要属性:进程共享属性,健壮属性,类型属 ...
- Linux下C的线程同步机制
C里提供了保证线程安全性的三种方法: (添加头文件#include<pthread.h>,pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a, ...
随机推荐
- Drozer安装
(1)JDK安装 http://www.cnblogs.com/linbc/p/4319509.html http://blog.csdn.net/qq_31988895/article/detail ...
- chrome开发配置(三)安装开发工具
1.安装 VisualStudio2010,设置环境变量 GYP_MSVS_VERSION=2010 2.安装 VisualStudio2010 SP1 3.安装 windows 8.0 sdk(不要 ...
- html 用图片代替重置按钮
提交时,若把按钮设置成图片提交特别方便只要 <input type="image" alt="点此提交" src="images/button. ...
- javaScript初学者易错点
大家好,这是我在博客园写的第一篇博文.作为一名前端开发初学者,由于经验不足,水平有限,在做项目的过程中总会遇到这样或那样的问题,每每这时候,我都比较喜欢到博客园这里来寻求解决方案,结果也总是能找到满意 ...
- 安全删除mysql binlog日志
命令行下执行 show binary logs; purge binary logs to 'mysql-bin.000070';
- remove duplicates in Postgres(sql去重)
A frequent question in IRC is how to delete rows that are duplicates over a set of columns, keeping ...
- jsonp从服务器读取数据并且予以显示
之前看了许多的关于jsonp的文章,大多是讲的比较的模糊的,下面是我的个人的理解! 基于这样的一段代码,做下解释: 这是在jsonp中读取数据的时候(取出来当然是json的格式json格式不清楚的,可 ...
- JAVA字符串格式化-String.format()的使用 (转载)
常规类型的格式化 String类的format()方法用于创建格式化的字符串以及连接多个字符串对象.熟悉C语言的同学应该记得C语言的sprintf()方法,两者有类似之处.format()方法有两种重 ...
- STM32-F0/F1/F2
用到的资源是:A.ST公司提供:STM32F10x开发标准库V3.5B.实验平台:战舰开发板V2.1C.编译软件:MDK3.8D.编辑软件:Source Insight_V3.5E.RTOS:ucos ...
- blocked because of many connection errors; unblock with 'mysqladmin flush-hosts;MySQL在远程访问时非常慢的解决方法;MySql链接慢的解决方法
一:服务器异常:Host 'xx.xxx.xx.xxx' is blocked because of many connection errors; unblock with 'mysqladmin ...