Sobes.tech
Junior — Middle

Is it mandatory for each thread to access a shared global variable?

sobes.tech AI

Answer from AI

Access to a shared global variable from multiple threads is not necessarily allowed by default. In a multithreaded application, access to a shared global variable must be synchronized to avoid race conditions and unpredictable behavior.

If multiple threads read and write to the same global variable simultaneously without synchronization mechanisms (such as mutexes, atomic operations), this can lead to errors.

Example of using a mutex to protect a global variable in C++:

#include <mutex>

int global_var = 0;
std::mutex mtx;

void thread_func() {
    std::lock_guard<std::mutex> lock(mtx);
    global_var++;
}

Therefore, not every thread is allowed to access a global variable without control — proper synchronization must be ensured.