WINAPI Implementing Mutex Locks

Source: Internet
Author: User

# 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, &AMP;UITHREADID1); HThread2 = (HANDLE) _beginthreadex (NULL,0, &startthread, (void*) PMSG2,0, &AMP;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

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.