"Go" implements multi-threaded mutex lock (WIN32) in C + +

Source: Internet
Author: User
Tags mutex

Original Chexlong original address: http://blog.csdn.net/chexlong/article/details/7051193

Purpose of this article: to implement thread synchronization locks with C + + and Windows Mutex objects (mutexes).

Preparation knowledge: 1, the working mechanism of the kernel object mutex (mutex), the use of the WaitForSingleObject function, which can be obtained from MSDN, 2, when two or more threads need to access a shared resource at the same time, The system needs to use a synchronization mechanism to ensure that only one thread is using the resource at a time. A Mutex is a synchronization primitive that grants exclusive access to a shared resource to only one thread. If a thread acquires a mutex, the second thread to get the mutex is suspended until the first thread releases the mutex.

Below is my reference to the Open source project C + + sockets code, write the thread lock class

Lock.h

[CPP]View Plaincopy
  1. #ifndef _lock_h
  2. #define _lock_h
  3. #include <windows.h>
  4. Lock Interface Class
  5. Class Imylock
  6. {
  7. Public
  8. Virtual ~imylock () {}
  9. virtual void Lock () const = 0;
  10. virtual void Unlock () const = 0;
  11. };
  12. Mutex object Lock Class
  13. Class Mutex: Public imylock
  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. Lock
  24. Class CLock
  25. {
  26. Public
  27. CLock (const imylock&);
  28. ~clock ();
  29. Private
  30. Const imylock& M_lock;
  31. };
  32. #endif

Lock.cpp

[CPP]View Plaincopy
  1. #include "Lock.h"
  2. Create an anonymous mutex object
  3. Mutex::mutex ()
  4. {
  5. M_mutex =:: CreateMutex (NULL, FALSE, NULL);
  6. }
  7. Destroys mutex objects, frees resources
  8. Mutex::~mutex ()
  9. {
  10. :: CloseHandle (M_mutex);
  11. }
  12. Ensure that the thread that owns the mutex has access to the protected resource on its own
  13. void Mutex::lock () const
  14. {
  15. DWORD d = WaitForSingleObject (M_mutex, INFINITE);
  16. }
  17. Frees the mutex object owned by the current thread so that other threads can own the mutex and access the protected resource
  18. void Mutex::unlock () const
  19. {
  20. :: ReleaseMutex (M_mutex);
  21. }
  22. Automatic lock-out with C + + features
  23. Clock::clock (const imylock& m): M_lock (m)
  24. {
  25. M_lock. Lock ();
  26. }
  27. Automatic unlocking with C + + features
  28. Clock::~clock ()
  29. {
  30. M_lock. Unlock ();
  31. }

Below is the test code

[CPP]View Plaincopy
  1. MyLock.cpp: Defines the entry point of the console application.
  2. //
  3. #include <iostream>
  4. #include <process.h>
  5. #include "Lock.h"
  6. Using namespace std;
  7. Create a Mutex object
  8. Mutex G_lock;
  9. Thread functions
  10. unsigned int __stdcall startthread (void *pparam)
  11. {
  12. char *pmsg = (char *) pparam;
  13. if (!pmsg)
  14. {
  15. return (unsigned int) 1;
  16. }
  17. //Lock the protected resource (the following print statement) automatically
  18. //Before the thread function ends, automatically unlocks
  19. CLock Lock (G_lock);
  20. For ( int i = 0; i < 5; i++)
  21. {
  22. cout << pMsg << Endl;
  23. Sleep (500);
  24. }
  25. return (unsigned int) 0;
  26. }
  27. int main (int argc, char* argv[])
  28. {
  29. HANDLE HThread1, hThread2;
  30. unsigned int uiThreadId1, UITHREADID2;
  31. char *PMSG1 = "First print thread.";
  32. char *pmsg2 = "Second print Thread.";
  33. //Create two worker threads, print different messages individually
  34. //hthread1 =:: CreateThread (NULL, 0, (Lpthread_start_routine) Startthread, (void *) PMSG1, 0, (Lpdword) &  UITHREADID1);
  35. //hthread2 =:: CreateThread (NULL, 0, (Lpthread_start_routine) Startthread, (void *) PMSG2, 0, (Lpdword) &  UITHREADID2);
  36. HThread1 = (HANDLE) _beginthreadex (NULL, 0, &startthread, (void *) PMSG1, 0, &UITHREADID1);
  37. HThread2 = (HANDLE) _beginthreadex (NULL, 0, &startthread, (void *) PMSG2, 0, &UITHREADID2);
  38. //wait for thread to end
  39. DWORD dwret = WaitForSingleObject (hthread1,infinite);
  40. if (Dwret = = wait_timeout)
  41. {
  42. TerminateThread (hthread1,0);
  43. }
  44. Dwret = WaitForSingleObject (hthread2,infinite);
  45. if (Dwret = = wait_timeout)
  46. {
  47. TerminateThread (hthread2,0);
  48. }
  49. //Close thread handle to release resources
  50. :: CloseHandle (HTHREAD1);
  51. :: CloseHandle (HTHREAD2);
  52. System ("pause");
  53. return 0;
  54. }

Compile with VC2005, start the program, below is

If you stare at the code in the thread function, recompile the code, run

[CPP]View Plaincopy
    1. CLock Lock (G_lock);

The results see

Thus, by using the encapsulation class of the mutex, we can achieve the purpose of multi-thread synchronization. Because a mutex belongs to a kernel object, it is slow to perform multi-threaded synchronization, but it can be synchronized between multiple threads in different processes with a mutex.

In practical applications, we usually use critical sections and critical_section, called Key code snippets, in the next blog, I'll add critical_section locks to the mutex and Critical_ The performance of the section is made to compare.

"Go" implements multi-threaded mutex lock (WIN32) in C + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.