C11 thread Management: Atomic variables & monotone functions

Source: Internet
Author: User
Tags mutex

1. Atomic variables

C++11 provides an atomic type of STD::ATOMIC<T>, which can be used as a template parameter, using an atomic variable without the need to protect the variable with a mutex, which is more concise.

For example, if you want to make a counter, use the mutex and use the atomic variable in the following sequence:

//using mutexes structcounter{intvalue;    Std::mutex Mutex; voidincrement () {Std::lock_guard<std::mutex>Lock(mutex); ++value; }    voidDecrement () {Std::lock_guard<std::mutex>Lock(mutex); --value; }    int Get()    {        returnvalue; }};intMain () {return 0;}//using atomic variables#include <atomic>structcounter{std::atomic<int>value; voidincrement () {++value; }    voidDecrement () {--value; }    int Get()    {        returnvalue; }};
2, Call_once/once_flag

Monotonic functions are in a multithreaded environment, to ensure that a function is called only once, such as to initialize an object, and this object can only be initialized once, you can use std::call_once to ensure that the function in a multithreaded environment is called only once. When using Std::call_once, a once_flag is required as an entry for the call_once.

as an entry for the call_once. #include<thread>#include<iostream>#include<mutex>Std::once_flag Flag;voiddo_once () {std::call_once (flag, [] () {std::cout<<"called once."<<Std::endl;});}intMain () {Std::thread T1 (do_once);    Std::thread T2 (do_once);    std::thread t3 (do_once);    T1.join ();    T2.join ();    T3.join (); return 0;}//Output:Called once.

C11 thread Management: Atomic variables & monotone functions

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.