【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, ...
随机推荐
- eclipse使用replace命令替换整个project/workspace的某个字符串
比如说为了在调试的时候方便,我的应用程序中有很多System.out.println() 调试好了,要发布了,如何把这些一次性注释掉呢?见下图
- Spring Boot MyBatis 通用Mapper插件集成
Mybatis在使用过程中需要三个东西,每张表对应一个XXMapper.java接口文件,每张表对应一个XXMapper.xml文件,每张表对应一个Entity的Java文件. 其中XXMappe ...
- TOMCAT服务器不写端口号、不写项目名访问项目、虚拟目录配置
一.不写端口. 这个问题都被问烂了,因为TOMCAT默认的访问端口为8080,而TCP/IP协议默认80端口访问,大家之所以看到别的网站都不写端口号是因为人家用的的80端口访问的,而80端口因为的TC ...
- URAL 1097 Square Country 2 离散化
一共才100个正方形,将所有正方形左下角和右上角的X坐标和Y坐标离散化,直接枚举新建公园的点的坐标即可. O(n^3)的时间复杂度. #include <cstdio> #include ...
- 【转】HashMap的工作原理
很好的文章,推荐Java的一个好网站:ImportNew HashMap的工作原理是近年来常见的Java面试题.几乎每个Java程序员都知道HashMap,都知道哪里要用HashMap,知道Hasht ...
- MySQL:创建、修改和删除表
其实对很多人来说对于SQL语句已经忘了很多,或者说是不懂很多,因为有数据库图形操作软件,方便了大家,但是我们不能忘记最根本的东西,特别是一些细节上的东西,可能你用惯了Hibernate,不用写SQL语 ...
- 正则表达式验证工具类RegexUtils.java
Java 表单注册常用正则表达式验证工具类,常用正则表达式大集合. 1. 电话号码 2. 邮编 3. QQ 4. E-mail 5. 手机号码 6. URL 7. 是否为数字 8. 是否为中文 9. ...
- SQLServer2008 行转列2
with a as ( select numb,name,row_number() over( partition by numb order by name desc) rowid from fen ...
- 头文件中的#ifndef/#define/#endif 的作用
在一个大的软件工程里面,可能会有多个文件同时包含一个头文件,当这些文件编译链接成一个可执行文件时,就会出现大量重定义的错误.在头文件中实用#ifndef #define #endif能避免头文件的重定 ...
- You can't specify target table 'charge' for update in FROM clause
mysql中不能这么用. (等待mysql升级吧)错误提示就是说,不能先select出同一表中的某些值,再update这个表(在同一语句中) 替 换方 案: create table tmp as s ...