C++11 Multi-threaded learning note two mutex use

Source: Internet
Author: User

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

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.