博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
多线程相互排斥--mutex
阅读量:5776 次
发布时间:2019-06-18

本文共 12498 字,大约阅读时间需要 41 分钟。

     多线程之线程同步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 
. ** ** 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
typedef pthread_mutex_t OST_MUTEX_SECTION;#endifOST_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 * -
OST_FALSE if the mutex is already held by another thread * -
OST_TRUE 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 * -
OST_TRUE if the mutex was successfully locked. * -
OST_FALSE 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 
. ** ** 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_BEGINOSTMutex::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 
. ** ** 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_BEGINOSTMutex::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

转载于:https://www.cnblogs.com/clnchanpin/p/7047583.html

你可能感兴趣的文章
[Android Pro] Android libdvm.so 与 libart.so
查看>>
《响应式web设计》读书笔记(四)HTML5与CSS3
查看>>
[Step By Step]SAP HANA PAL多元指数回归预测分析Multiple Exponential Regression编程实例FORECASTWITHEXPR(预测)...
查看>>
JS魔法堂:mmDeferred源码剖析
查看>>
人不成熟的六大特征
查看>>
神经网络入门指南
查看>>
Spring Boot的启动器Starter详解
查看>>
WITH (NOLOCK)
查看>>
HTAP数据库 PostgreSQL 场景与性能测试之 24 - (OLTP) 物联网 - 时序数据并发写入(含时序索引BRIN)...
查看>>
说说搜索引擎中的人工干预
查看>>
克服大数据集群的挑战
查看>>
Linux下搭建MySQL集群
查看>>
物联网将让数据中心更为复杂,但更加有趣
查看>>
传Facebook研发新功能 发布合作媒体的专门内容
查看>>
美国国土安全部部长约翰逊就Dyn网络攻击事件发表声明
查看>>
《大数据原理:复杂信息的准备、共享和分析》一一2.6 单向哈希函数
查看>>
开放式网络是实现创新的快速通道
查看>>
《计算机网络课程设计(第2版)》——1.1节计算机网络课程的教学特点
查看>>
震惊!5分钟买到上千个银行卡密码!揭秘盗取银行卡信息三大方法....
查看>>
Marvell展示物联网和无线宽带解决方案
查看>>