Junior — Middle
Have you used std::atomic type and worked with atomic operations in C++ in your projects?
sobes.tech AI
Answer from AI
Yes, in C++ I used the std::atomic type for working with atomic operations, which allows safely modifying variables in a multithreaded environment without using mutexes.
std::atomic guarantees that read and write operations are atomic, preventing race conditions.
Example of using std::atomic:
#include <atomic>
#include <thread>
#include <iostream>
std::atomic<int> counter(0);
void increment() {
for (int i = 0; i < 1000; ++i) {
counter.fetch_add(1, std::memory_order_relaxed);
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Counter: " << counter.load() << std::endl;
return 0;
}
In this example, two threads simultaneously increase the counter, and thanks to std::atomic, the final value will be correct.