Thread Synchronization mutex

Source: Internet
Author: User
Mutex object 1. Create a handle type variable handle hmutex;
 
 
 
2. hmutex = createmutex (null, true, "ticket"); createmutex creates a mutex object
 
(Call releasemutex (hmutex) in time after successful creation to reduce the count by one .)
 
 
 
Iii. waitforsingleobject (hmutex, infinite); use this function where synchronization is needed.
 
 
 
 
4. releasemutex (hmutex); use this function to release the mutex lock after a waiting object is used. example # include <windows. h> # include <iostream. h> DWORD winapi fun1proc (lpvoidlpparameter // thread data); DWORD winapi fun2proc (lpvoid lpparameter/thread data); int ticket = 100; handle hmutex; void main () {handle handle1; handle handle2; handle1 = createthread (null, 0, fun1proc, null, 0, null); handle2 = createthread (null, 0, fun2proc, null, 0, null); closehandle (handl E1); closehandle (handle2); hmutex = createmutex (null, true, "ticket"); If (hmutex) {If (error_already_exists = getlasterror ()) {cout <"thereis already have a instance runing !!! "<Endl; return ;}/// waitforsingleobject (hmutex, infinite); // releasemutex (hmutex); sleep (4000 );} DWORD winapi fun1proc (lpvoid lpparameter // thread data) {While (true) {waitforsingleobject (hmutex, infinite); If (ticket> 0) {sleep (1 ); cout <"thisis fun1proc succeeded" <ticket -- <Endl;} else {break;} releasemutex (hmutex);} waitforsingleobject (hmutex, infinite ); cout <"fun1procrunning" <Endl; releasemutex (hmutex); Return 0;} DWORD winapi fun2proc (lpvoid lpparameter // thread data) {While (true) {waitforsingleobject (hmutex, infinite); If (ticket> 0) {sleep (1); cout <"thisis fun2proc restart" <ticket -- <Endl;} else {break ;} releasemutex (hmutex);} waitforsingleobject (hmutex, infinite); cout <"fun2procrunning" <Endl; releasemutex (hmutex); Return 0 ;}

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.