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
- #ifndef _lock_h
- #define _lock_h
- #include <windows.h>
- Lock Interface Class
- Class Imylock
- {
- Public
- Virtual ~imylock () {}
- virtual void Lock () const = 0;
- virtual void Unlock () const = 0;
- };
- Mutex object Lock Class
- Class Mutex: Public imylock
- {
- Public
- Mutex ();
- ~mutex ();
- virtual void Lock () const;
- virtual void Unlock () const;
- Private
- HANDLE M_mutex;
- };
- Lock
- Class CLock
- {
- Public
- CLock (const imylock&);
- ~clock ();
- Private
- Const imylock& M_lock;
- };
- #endif
Lock.cpp
[CPP]View Plaincopy
- #include "Lock.h"
- Create an anonymous mutex object
- Mutex::mutex ()
- {
- M_mutex =:: CreateMutex (NULL, FALSE, NULL);
- }
- Destroys mutex objects, frees resources
- Mutex::~mutex ()
- {
- :: CloseHandle (M_mutex);
- }
- Ensure that the thread that owns the mutex has access to the protected resource on its own
- void Mutex::lock () const
- {
- DWORD d = WaitForSingleObject (M_mutex, INFINITE);
- }
- Frees the mutex object owned by the current thread so that other threads can own the mutex and access the protected resource
- void Mutex::unlock () const
- {
- :: ReleaseMutex (M_mutex);
- }
- Automatic lock-out with C + + features
- Clock::clock (const imylock& m): M_lock (m)
- {
- M_lock. Lock ();
- }
- Automatic unlocking with C + + features
- Clock::~clock ()
- {
- M_lock. Unlock ();
- }
Below is the test code
[CPP]View Plaincopy
- MyLock.cpp: Defines the entry point of the console application.
- //
- #include <iostream>
- #include <process.h>
- #include "Lock.h"
- Using namespace std;
- Create a Mutex object
- Mutex G_lock;
- Thread functions
- unsigned int __stdcall startthread (void *pparam)
- {
- char *pmsg = (char *) pparam;
- if (!pmsg)
- {
- return (unsigned int) 1;
- }
- //Lock the protected resource (the following print statement) automatically
- //Before the thread function ends, automatically unlocks
- CLock Lock (G_lock);
- For ( int i = 0; i < 5; i++)
- {
- cout << pMsg << Endl;
- Sleep (500);
- }
- return (unsigned int) 0;
- }
- int main (int argc, char* argv[])
- {
- HANDLE HThread1, hThread2;
- unsigned int uiThreadId1, UITHREADID2;
- char *PMSG1 = "First print thread.";
- char *pmsg2 = "Second print Thread.";
- //Create two worker threads, print different messages individually
- //hthread1 =:: CreateThread (NULL, 0, (Lpthread_start_routine) Startthread, (void *) PMSG1, 0, (Lpdword) & UITHREADID1);
- //hthread2 =:: CreateThread (NULL, 0, (Lpthread_start_routine) Startthread, (void *) PMSG2, 0, (Lpdword) & UITHREADID2);
- HThread1 = (HANDLE) _beginthreadex (NULL, 0, &startthread, (void *) PMSG1, 0, &UITHREADID1);
- HThread2 = (HANDLE) _beginthreadex (NULL, 0, &startthread, (void *) PMSG2, 0, &UITHREADID2);
- //wait for thread to end
- DWORD dwret = WaitForSingleObject (hthread1,infinite);
- if (Dwret = = wait_timeout)
- {
- TerminateThread (hthread1,0);
- }
- Dwret = WaitForSingleObject (hthread2,infinite);
- if (Dwret = = wait_timeout)
- {
- TerminateThread (hthread2,0);
- }
- //Close thread handle to release resources
- :: CloseHandle (HTHREAD1);
- :: CloseHandle (HTHREAD2);
- System ("pause");
- return 0;
- }
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
- 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 + +