1111111.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <thread> #include <mutex> int gcounter = 0;STD: : Mutex gmtx; Std::mutex Gmtxoutput;void increases () {for (int i = 0; i<10000; ++i) {if (Gmtx.try_lock ())} { //only increase if C urrently not Locked:++gcounter;gmtx.unlock ();} Else{gmtxoutput.lock (); Std::cout << "Try lock failed" << Std::endl;gmtxoutput.unlock ();}} int _tmain (int argc, _tchar* argv[]) {std::thread threads[10];for (int i = 0; i<10; ++i) threads[i] = Std::thread (Increa SES); for (auto& th:threads) Th.join (), Std::cout << "counter is" << gcounter << Std::endl;return 0 ;}
Output:
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Try Lock failed
Counter is 99983
Please press any key to continue ...
This example illustrates the difference between try_lock () and lock ().
Try_lock () Tests for locking and returns a Boolean value
Lock () is locked without locking and is blocked until locked
C++11 Multi-threaded learning note two mutex use