# mutex73 # [email protected]# Now in Xidian University
Streamlined the online program.
//Lock.h#pragma once#include <windows.h>class Mutex {public: Mutex() { m_mutex = ::CreateMutex(NULL, FALSE, NULL); } ~Mutex() { ::CloseHandle(m_mutex); } virtualvoidconst { DWORD d = WaitForSingleObject(m_mutex, INFINITE); } virtualvoidconst { ::ReleaseMutex(m_mutex); }private: HANDLE m_mutex;};
//main.cpp#include <iostream>#include <process.h>#include "Lock.h"using namespace STD; Mutex G_lock;unsigned int__stdcall Startthread (void*pparam) {Char*pmsg = (Char*) Pparam;if(!pmsg) {return(unsigned int)1; } g_lock.lock (); for(inti =0; I <5; i++) {cout<< PMSG << Endl; Sleep ( -); } g_lock.unlock ();return(unsigned int)0;}intMainintargcChar* argv[]) {HANDLE hThread1, hThread2;unsigned intUiThreadId1, UITHREADID2;Char*PMSG1 ="First print thread.";Char*PMSG2 ="Second print thread."; HThread1 = (HANDLE) _beginthreadex (NULL,0, &startthread, (void*) PMSG1,0, &UITHREADID1); HThread2 = (HANDLE) _beginthreadex (NULL,0, &startthread, (void*) PMSG2,0, &UITHREADID2); DWORD Dwret = WaitForSingleObject (hthread1,infinite);if(Dwret = = wait_timeout) {TerminateThread (HThread1,0); } Dwret = WaitForSingleObject (hthread2,infinite);if(Dwret = = wait_timeout) {TerminateThread (hThread2,0); }:: CloseHandle (HTHREAD1); :: CloseHandle (HTHREAD2); System"Pause");return 0;}
Results:
printprintprintprintprintprintprintprintprintprint thread.请按任意键继续. . .
Memo:
Each signal acquires a mutex and is WaitForSingleObject, which is waiting for the unlock of the previous fetch resource thread, when ReleaseMutex occurs, WaitForSingleObject will return the next thread to get the resources
WINAPI Implementing Mutex Locks