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

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
RELATED COURSES

View all Courses

Keep Exploring