DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

std::atomic c++11

atomic

As its name, its atomic in nature that mean it offers operations that are guaranteed as mutex protected in critical section. It will be used to provide the concurrent access to global data from multiple threads without using mutex. Example: Write/Read the global variable and it is accessed by multiple threads.

Purpose

When we have concurrent scenario then we can directly use atomic. I mean that no need to use any lock, it internally manage it. we can save writing effort.

std::atomic<boo>bvar =  bool variable + lock_guard

With atomic:

//Global Variable
std::atomic<bool> bvar(false);
//Inside thread
bvar.store(true)

Without atomic:

//Global Variable
bool bvar = false;
std::mutex m;
//Inside thread
{
    std::lock_guard<std::mutex> lg(m);
    bvar=true;
}

Sample Code with example:

/*
Program: Atomic 
Author: Alpha Master
Date: 6 Feb 2021
*/

//Header File
#include<iostream>
#include<thread>
#include<atomic>
#include<chrono>

//Global Variable
int gValue;

//Atomic variable
std::atomic<bool> g_ab_ready(false);

//Reader Thread
void ReadThread()
{
    while(!g_ab_ready.load())
    {
        std::cout<<"!!!Waiting, variable is NOT ready"<<std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    //Go the value
    std::cout<<"Got the value:"<<gValue<<std::endl;
}

//Writer Thread
void WriteThread()
{
    //Write the value
    gValue = 50;
    std::cout<<"Wrote the value, make true to atomic"<<std::endl;
    g_ab_ready.store(true);
}

int main()
{
    std::cout<<"Atomic Functionality"<<std::endl;
	
    //Thread 1 and its joinable
    std::thread t1(ReadThread);
   
    //Thread 2 and its also joinable
    std::thread t2(WriteThread);

    std::cout<<"Main thread is Waiting for Child thread"<<std::endl;
    t1.join();
    t2.join();

    return 0;
};

Output:

Atomic Functionality
!!!Waiting, variable is NOT ready
Main thread is Waiting for Child thread
Wrote the value, make true to atomic
Got the value:50

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer