Sobes.tech
Junior — Middle

What distinguishes the use of std::mutex from std::atomic in data access management?

sobes.tech AI

Answer from AI

std::mutex and std::atomic are used to ensure safe access to data in a multithreaded environment, but they work differently.

  • std::mutex is a locking mechanism that allows one thread to exclusively own a resource. Other threads trying to acquire the mutex will wait until it is released. This is suitable for protecting complex data structures or critical sections where operations cannot be atomic.

  • std::atomic provides atomic operations on individual variables (e.g., integers) without locks. It is a lighter and faster synchronization method but limited to simple types and operations.

Example of using std::atomic for a counter:

#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;
    return 0;
}

If you need to protect a complex data structure, such as a vector, you can use std::mutex:

#include <mutex>
#include <vector>

std::vector<int> data;
std::mutex mtx;

void add_data(int value) {
    std::lock_guard<std::mutex> lock(mtx);
    data.push_back(value);
}

Thus, std::atomic is effective for simple atomic operations, while std::mutex is used to protect more complex critical sections.