I have an application that I'm trying to make multithreaded. Each thread will access a large chunk of read-only data.
Is is okay if multiple threads access the data simultaneously? I know that if the data were not read-only, I would need to use mutexes or some other form of synchronization to prevent race-conditions. But I'm wondering if it's okay to read the data without regard to synchronization.
The data in question will not be modified for the duration of all threads. The application will be running on Linux and Windows and is written in C++ if that makes any difference.
Multiple threads accessing shared data simultaneously may lead to a timing dependent error known as data race condition. Data races may be hidden in the code without interfering or harming the program execution until the moment when threads are scheduled in a scenario (the condition) that break the program execution.
When race conditions occur. A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable.
If the data we share is read-only data, there will be no problem, because the data read by one thread is unaffected by whether or not another thread is reading the same data. However, once data is shared between threads, and one or more threads start modifying the data, and that's the start of problems.
Unlike with isolated programs, threads share the same memory space, so two threads can read and write anything in each other's memory at the same time. Threads each have their own registers and stack areas, but the stacks are each in their own area of the same memory space.
If the data is read-only for the lifetime of all the threads that read it, then yes, it's perfectly fine to read without synchronization.
If the data is truly read-only for the duration of the multi-threaded access, then no synchronization is necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With