Junior — Middle
Explain the purpose and operation of std::atomic in C++.
sobes.tech AI
Answer from AI
std::atomic in C++ is designed to provide atomic operations on variables, which is important when working with multithreading. Atomic operations guarantee that reading or writing a variable's value occurs entirely, without interruptions, preventing race conditions and incorrect data.
For example, if multiple threads simultaneously increment a counter, using a regular variable can lead to errors. With std::atomic<int>, increment operations are safe without additional synchronization:
#include <atomic>
#include <thread>
#include <vector>
#include <iostream>
std::atomic<int> counter(0);
void increment() {
for (int i = 0; i < 1000; ++i) {
++counter; // atomic increment
}
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i) {
threads.emplace_back(increment);
}
for (auto& t : threads) {
t.join();
}
std::cout << "Counter: " << counter << std::endl; // Expected 10000
}
Thus, std::atomic helps write safe multithreaded code without using mutexes for simple operations.