Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wise to access read-only data from multiple threads simultaneously?

Tags:

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.

like image 730
Nathan Osman Avatar asked Apr 13 '11 00:04

Nathan Osman


People also ask

What will happen if multiple threads accessing the same resource?

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.

Can multiple threads read the same value?

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.

Is read only data thread safe?

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.

Can two threads read memory at the same time?

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.


2 Answers

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.

like image 75
R. Martinho Fernandes Avatar answered Sep 29 '22 05:09

R. Martinho Fernandes


If the data is truly read-only for the duration of the multi-threaded access, then no synchronization is necessary.

like image 29
ThomasMcLeod Avatar answered Sep 29 '22 06:09

ThomasMcLeod