多线程相互排斥--mutex
多线程之线程同步Mutex (功能与Critial Sections同样,可是属于内核对象,訪问速度较慢。能够被不同进程调用)
一 Mutex
相互排斥对象(mutex)内核对象可以确保线程拥有对单个资源的相互排斥訪问权。实际上相互排斥对象是因此而得名的。相互排斥对象包括一个使用数量,一个线程ID和一个递归计数器。
相互排斥对象的行为特性与关键代码段同样。可是相互排斥对象属于内核对象,而关键代码段则属于用户方式对象。这意味着相互排斥对象的执行速度比关键代码段要慢。可是这也意味着不同进程中的多个线程可以訪问单个相互排斥对象。而且这意味着线程在等待訪问资源时可以设定一个超时值。
ID用于标识系统中的哪个线程当前拥有相互排斥对象,递归计数器用于指明该线程拥有相互排斥对象的次数。
相互排斥对象有很多用途,属于最经常使用的内核对象之中的一个。通常来说,它们用于保护由多个线程訪问的内存块。假设多个线程要同一时候訪问内存块。内存块中的数据就可能遭到破坏。相互排斥对象可以保证訪问内存块的不论什么线程拥有对该内存块的独占訪问权。这样就行保证数据的完整性。
/*****************************************************************************
* OpenST Basic tool library *
* Copyright (C) 2014 Henry.Wen renhuabest@sina.com . *
* *
* This file is part of OST. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 3 as *
* published by the Free Software Foundation. *
* *
* You should have received a copy of the GNU General Public License *
* along with OST. If not, see <http://www.gnu.org/licenses/>. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
* Author : Henry.Wen *
* E-Mail : renhuabest@sina.com *
* License : GNU General Public License (GPL) *
* source code availability:https://github.com/henrywen2011/OST *
* *
*----------------------------------------------------------------------------*
* Remark : Description *
*----------------------------------------------------------------------------*
* Change History : *
* Date | Version | Author | Description *
*----------------------------------------------------------------------------*
* 2014/01/26 | 1.0.0.1 | Henry.Wen | Create file *
*----------------------------------------------------------------------------*
* *
*****************************************************************************/
#ifndef OST_CORE_OSTMUTEX_H
#define OST_CORE_OSTMUTEX_H #include "OSTTypes.h"
#include "OSTPlatform.h"
#include "OSTBasicable.h" #if (OST_PLAFORM == OST_PLATFORM_WIN32)
typedef CRITICAL_SECTION OST_MUTEX_SECTION;
#else
#include <pthread>
typedef pthread_mutex_t OST_MUTEX_SECTION;
#endif OST_NAMESPACE_BEGIN
/**
* @class OSTMutex
* @brief A Mutex (mutual exclusion) is a synchronization mechanism used to control
* access to a shared resourcein a concurrent (multithreaded) scenario.
*/
class OSTMutex : public NonCopyable
{
public:
OSTMutex(void);
~OSTMutex(void); /**
* @brief Locks the OSTMutex. Blocks if the OSTMutex is held by another thread.
*/
void Lock() const; /**
* @brief Unlocks the mutex so that it can be acquired by other threads.
*/
void Unlock() const; /**
* @brief Tries to lock the mutex.
* @return
* -<em>OST_FALSE</em> if the mutex is already held by another thread
* -<em>OST_TRUE</em> otherwise.
*/
OSTBool TryLock(); /**
* @brief Locks the mutex. Blocks up to the given number of milliseconds
* if the mutex is held by another thread.
* Performance Note: On most platforms (including Windows), this member function is
* implemented using a loop calling (the equivalent of) tryLock() and Thread::sleep().
* On POSIX platforms that support pthread_mutex_timedlock(), this is used.
*
* @return
* - <em>OST_TRUE</em> if the mutex was successfully locked.
* - <em>OST_FALSE</em> otherwise.
*/
OSTBool TryLock(long millisecondes); private:
mutable OST_MUTEX_SECTION m_mutex;
}; /**
* @class AutoLock
* @brief Using the AutoLock class is the preferred way to automatically
* lock and unlock a mutex.
*/
class AutoLock
{
public:
AutoLock(const OSTMutex& mutex, OSTBool autolocked = OST_TRUE) : m_mutex(mutex), m_locked(autolocked)
{
if(autolocked)
{
m_mutex.Lock();
m_locked = autolocked;
}
}; ~AutoLock()
{
if(m_locked)
{
m_mutex.Unlock();
}
}; private:
AutoLock(const AutoLock&);
AutoLock& operator = (const AutoLock&); private:
const OSTMutex& m_mutex;
OSTBool m_locked;
}; /**
* @class AutoUnLock
* @brief Using the AutoUnLock class is the preferred way to automatically
* lock and unlock a mutex.
*/
class AutoUnLock
{
public:
AutoUnLock(const OSTMutex& mutex, OSTBool unlocked = OST_TRUE) : m_mutex(mutex), m_unlocked(unlocked)
{
if(m_unlocked)
{
m_mutex.Unlock();
}
} ~AutoUnLock()
{
m_mutex.Lock();
} private:
AutoUnLock(const AutoUnLock&);
AutoUnLock& operator = (const AutoUnLock&); private:
const OSTMutex& m_mutex;
OSTBool m_unlocked;
}; #define LOCK(mutex) AutoLock locker(mutex)
#define UNLOCK(mutex) AutoUnLock locker(mutex) OST_NAMESPACE_END #endif//OST_CORE_OSTMUTEX_H
OSTMutex_POSIX.cpp
/*****************************************************************************
* OpenST Basic tool library *
* Copyright (C) 2014 Henry.Wen renhuabest@sina.com . *
* *
* This file is part of OST. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 3 as *
* published by the Free Software Foundation. *
* *
* You should have received a copy of the GNU General Public License *
* along with OST. If not, see <http://www.gnu.org/licenses/>. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
* Author : Henry.Wen *
* E-Mail : renhuabest@sina.com *
* License : GNU General Public License (GPL) *
* source code availability:https://github.com/henrywen2011/OST *
* *
*----------------------------------------------------------------------------*
* Remark : Description *
*----------------------------------------------------------------------------*
* Change History : *
* Date | Version | Author | Description *
*----------------------------------------------------------------------------*
* 2014/01/24 | 1.0.0.1 | Henry.Wen | Create file *
*----------------------------------------------------------------------------*
* *
*****************************************************************************/
#include "OSTBaseExc.h"
#include "OSTMutex.h" OST_NAMESPACE_BEGIN OSTMutex::OSTMutex(void)
{
pthread_mutexattr_t attr; if( 0 != pthread_mutexattr_init(&attr) || 0 != pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE))
return; if (0 != pthread_mutex_init(&m_mutex, &attr))
{
pthread_mutexattr_destroy(&attr);
throw SystemExc("cannot create mutex");
}
pthread_mutexattr_destroy(&attr);
} OSTMutex::~OSTMutex(void)
{
pthread_mutex_destroy(&m_mutex);
} void OSTMutex::Lock() const
{
try
{
pthread_mutex_lock(&m_mutex);
}
catch (...)
{
throw SystemExc("Cannot lock mutex");
}
} void OSTMutex::Unlock() const
{
pthread_mutex_unlock(&m_mutex);
} OSTBool OSTMutex::TryLock()
{
OSTInt32 rc = pthread_mutex_trylock(&m_mutex);
if (0 == rc)
{
return OST_TRUE;
}
else if (rc == EBUSY)
{
return OST_FALSE;
}
else
{
throw SystemExc("Cannot lock mutex");
}
} OSTBool OSTMutex::TryLock(long millisecondes)
{
return OST_TRUE;
} OST_NAMESPACE_END
OSTMutex_Win32.cpp
/*****************************************************************************
* OpenST Basic tool library *
* Copyright (C) 2014 Henry.Wen renhuabest@sina.com . *
* *
* This file is part of OST. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 3 as *
* published by the Free Software Foundation. *
* *
* You should have received a copy of the GNU General Public License *
* along with OST. If not, see <http://www.gnu.org/licenses/>. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
* Author : Henry.Wen *
* E-Mail : renhuabest@sina.com *
* License : GNU General Public License (GPL) *
* source code availability:https://github.com/henrywen2011/OST *
* *
*----------------------------------------------------------------------------*
* Remark : Description *
*----------------------------------------------------------------------------*
* Change History : *
* Date | Version | Author | Description *
*----------------------------------------------------------------------------*
* 2014/01/24 | 1.0.0.1 | Henry.Wen | Create file *
*----------------------------------------------------------------------------*
* *
*****************************************************************************/
#include "OSTBaseExc.h"
#include "OSTMutex.h" OST_NAMESPACE_BEGIN OSTMutex::OSTMutex(void)
{
InitializeCriticalSectionAndSpinCount(&m_mutex, 4000);
} OSTMutex::~OSTMutex(void)
{
DeleteCriticalSection(&m_mutex);
} void OSTMutex::Lock() const
{
try
{
EnterCriticalSection(&m_mutex);
}
catch (...)
{
throw SystemExc("Cannot lock mutex");
}
} void OSTMutex::Unlock() const
{
LeaveCriticalSection(&m_mutex);
} OSTBool OSTMutex::TryLock()
{
try
{
return (TryEnterCriticalSection(&m_mutex) != 0 ? OST_TRUE : OST_FALSE);
}
catch(...)
{
}
throw SystemExc("Cannot lock mutex");
} OSTBool OSTMutex::TryLock(long millisecondes)
{
return OST_TRUE;
} OST_NAMESPACE_END
多线程相互排斥--mutex的更多相关文章
- 多线程相互排斥--mutex(二)
不知道大家对多线程或多进程间的同步相互排斥的控制机制了解的怎么样,事实上有非常多种方法能够实现这个目的,可是这些方法事实上由4种最主要的方法实现.这4种最主要的方法详细定义例如以下:在这有讲得不正确的 ...
- android NDK编程:使用posix多线程与mutex相互排斥同步
MainActivity.java 调用原生方法 posixThreads(int threads, int iterations) 启动线程 package com.apress.threads; ...
- 【C/C++多线程编程之六】pthread相互排斥量
多线程编程之线程同步相互排斥量 Pthread是 POSIX threads 的简称,是POSIX的线程标准. Pthread线程同步指多个线程协调地,有序地同步使用共享 ...
- 数据共享之相互排斥量mutex
相互排斥量介绍 相互排斥量能够保护某些代码仅仅能有一个线程运行这些代码.假设有个线程使用相互排斥量运行某些代码,其它线程訪问是会被堵塞.直到这个线程运行完这些代码,其它线程才干够运行. 一个线程在訪问 ...
- Linux程序设计学习笔记----多线程编程线程同步机制之相互排斥量(锁)与读写锁
相互排斥锁通信机制 基本原理 相互排斥锁以排他方式防止共享数据被并发訪问,相互排斥锁是一个二元变量,状态为开(0)和关(1),将某个共享资源与某个相互排斥锁逻辑上绑定之后,对该资源的訪问操作例如以下: ...
- Linux多线程同步之相互排斥量和条件变量
1. 什么是相互排斥量 相互排斥量从本质上说是一把锁,在訪问共享资源前对相互排斥量进行加锁,在訪问完毕后释放相互排斥量上的锁. 对相互排斥量进行加锁以后,不论什么其它试图再次对相互排斥量加锁的线程将会 ...
- linux系统编程:线程同步-相互排斥量(mutex)
线程同步-相互排斥量(mutex) 线程同步 多个线程同一时候訪问共享数据时可能会冲突,于是须要实现线程同步. 一个线程冲突的演示样例 #include <stdio.h> #includ ...
- Android多线程研究(3)——线程同步和相互排斥及死锁
为什么会有线程同步的概念呢?为什么要同步?什么是线程同步?先看一段代码: package com.maso.test; public class ThreadTest2 implements Runn ...
- Linux互斥和同步应用程序(一):posix线程和线程之间的相互排斥
[版权声明:尊重原创,转载请保留出处:blog.csdn.net/shallnet 或 .../gentleliu,文章仅供学习交流.请勿用于商业用途] 有了进程的概念,为何还要使用线程呢? 首先,回 ...
随机推荐
- 小学生绞尽脑汁也学不会的python(异常,约束,MD5加密,日志处理)
小学生绞尽脑汁也学不会的python(异常,约束,MD5加密,日志处理) 异常处理(处理) 1.产生异常.raise 异常类(),抛出异常2. 处理异常: try: xxxxx # 尝试执行的代码. ...
- Unity3D——加入剑痕效果(PocketRPG Trail插件)
首先非常感谢大家的支持,因为近期项目吃紧,所以更新的速度可能会有点慢!希望大家谅解,当然大家的支持是我最大的动力.我也会尽我所能写出更好的文章,当然因为本人是个新手并且工作的内容也不是unity3D. ...
- Android Parcelable vs Serializable
序列化 在Android中.对象在实现序列化之前是无法直接作为Intent參数在Activity之间传递的. Android中对象序列化能够通过实现Serializable接口或者实现Parcelab ...
- 【LDA】动手实现LDA
这段时间对LDA比較感兴趣,尝试在工作中使用它.平时做想法的高速验证,都用的是"GibbsLDA++-0.2",一个c实现版本号的LDA. 这两天用c++ stl自己写了一个单机版 ...
- bzoj4808: 马 & bzoj3175: [Tjoi2013]攻击装置 (黑白染色+最小割)
bzoj4808: 马 & bzoj3175: [Tjoi2013]攻击装置 题目:传送门 简要题意: 和n皇后问题差不多,但是这里是每个棋子走日子,而且有些格子不能放棋子.求最多能放多少个棋 ...
- HTML5客户端数据存储机制Web Storage和Web SQL Database
引言 html5本地存储可以选择两种方式,一种是本地存储,一种是sqlite. 比如开发html5的购物车功能,就可以考虑选择其中之一,进行本地存储与操作. 又或者保存用户登录信息,可以使用local ...
- TensorFlow训练MNIST报错ResourceExhaustedError
title: TensorFlow训练MNIST报错ResourceExhaustedError date: 2018-04-01 12:35:44 categories: deep learning ...
- 07:清泉-改(prime+堆)
时间限制: 10000ms 单个测试点时间限制: 1000ms 内存限制: 512000kB 描述 华北电力大学可以抽象为一张有n个点m条边的无向图. 现在所有的边都断了. 修复每条边都有个不同 ...
- svn创建分支的做法
作者:朱金灿 来源:http://blog.csdn.net/clever101 1. 首先选择你要创建分支的工作目录,如下图: 2.选择要创建分支的路径.注释以及版本,选择HEADrevision ...
- sqluldr2linux64.bin的使用
使用sqluldr2linux64.bin的前提是已经安装了Oracle数据库,sqluldr2linux64.bin和Oracle在同一台主机上使用,使用之前需要赋予可执行权限: [root@nod ...