Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

atomic
type
c++
basics

What is atomic type in C++?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

Consider a multithreaded program with one shared variable. Now, imagine that all the threads are trying to access and modify this shared variable at the same time. This condition, known as a race condition, is a problem.

In order to solve this problem, C++ offers atomic variables that are thread-safe. The atomic type is implemented using mutex locks. If one thread acquires the mutex lock, then no other thread can acquire it until it is released by that particular thread.

How to use it

svg viewer

Code

In the code below, two threads (th1, th2) that share the atomic variable temp are created. Therefore, both of the threads can’t access temp at the same time.

#include <atomic>
#include <iostream>
#include <thread>
using namespace std;
// atomic variable
atomic <int> temp(0);
// thread one adds 5 in the temp.
void thread_one()
{
cout << "Inside Thread_one.\n";
temp += 5;
cout << temp << "\n";
}
// thread two subtracts 5 in the temp.
void thread_two()
{
cout << "Inside Thread_two.\n";
temp -= 5;
cout << temp << "\n";
}
//driver
int main()
{
// initiating threads
thread th1(thread_one);
thread th2(thread_two);
// waiting for the threads to end.
th1.join();
th2.join();
}

RELATED TAGS

atomic
type
c++
basics
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring