歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 互斥對象鎖和臨界區鎖性能比較

互斥對象鎖和臨界區鎖性能比較

日期:2017/3/1 10:46:50   编辑:Linux編程

在Win32平台上進行多線程編程,常會用到鎖。下邊用C++實現了互斥對象(Mutex)鎖和臨界區(CRITICAL_SECTION)鎖,以加深理解和今後方便使用。代碼已在VS2005環境下編譯測試通過。

Lock.h

  1. #ifndef _Lock_H
  2. #define _Lock_H
  3. #include <windows.h>
  4. //鎖接口類
  5. class ILock
  6. {
  7. public:
  8. virtual ~ILock() {}
  9. virtual void Lock() const = 0;
  10. virtual void Unlock() const = 0;
  11. };
  12. //互斥對象鎖類
  13. class Mutex : public ILock
  14. {
  15. public:
  16. Mutex();
  17. ~Mutex();
  18. virtual void Lock() const;
  19. virtual void Unlock() const;
  20. private:
  21. HANDLE m_mutex;
  22. };
  23. //臨界區鎖類
  24. class CriSection : public ILock
  25. {
  26. public:
  27. CriSection();
  28. ~CriSection();
  29. virtual void Lock() const;
  30. virtual void Unlock() const;
  31. private:
  32. CRITICAL_SECTION m_critclSection;
  33. };
  34. //鎖
  35. class CMyLock
  36. {
  37. public:
  38. CMyLock(const ILock&);
  39. ~CMyLock();
  40. private:
  41. const ILock& m_lock;
  42. };
  43. #endif

Lock.cpp

  1. #include "Lock.h"
  2. //---------------------------------------------------------------------------
  3. //創建一個匿名互斥對象
  4. Mutex::Mutex()
  5. {
  6. m_mutex = ::CreateMutex(NULL, FALSE, NULL);
  7. }
  8. //銷毀互斥對象,釋放資源
  9. Mutex::~Mutex()
  10. {
  11. ::CloseHandle(m_mutex);
  12. }
  13. //確保擁有互斥對象的線程對被保護資源的獨自訪問
  14. void Mutex::Lock() const
  15. {
  16. DWORD d = WaitForSingleObject(m_mutex, INFINITE);
  17. }
  18. //釋放當前線程擁有的互斥對象,以使其它線程可以擁有互斥對象,對被保護資源進行訪問
  19. void Mutex::Unlock() const
  20. {
  21. ::ReleaseMutex(m_mutex);
  22. }
  23. //---------------------------------------------------------------------------
  24. //初始化臨界資源對象
  25. CriSection::CriSection()
  26. {
  27. ::InitializeCriticalSection(&m_critclSection);
  28. }
  29. //釋放臨界資源對象
  30. CriSection::~CriSection()
  31. {
  32. ::DeleteCriticalSection(&m_critclSection);
  33. }
  34. //進入臨界區,加鎖
  35. void CriSection::Lock() const
  36. {
  37. ::EnterCriticalSection((LPCRITICAL_SECTION)&m_critclSection);
  38. }
  39. //離開臨界區,解鎖
  40. void CriSection::Unlock() const
  41. {
  42. ::LeaveCriticalSection((LPCRITICAL_SECTION)&m_critclSection);
  43. }
  44. //---------------------------------------------------------------------------
  45. //利用C++特性,進行自動加鎖
  46. CMyLock::CMyLock(const ILock& m) : m_lock(m)
  47. {
  48. m_lock.Lock();
  49. }
  50. //利用C++特性,進行自動解鎖
  51. CMyLock::~CMyLock()
  52. {
  53. m_lock.Unlock();
  54. }
Copyright © Linux教程網 All Rights Reserved