22

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.

Nathan Osman
  • 71,149
  • 71
  • 256
  • 361
  • While the general answer is already given, I'd like to add a warning. Be careful if the resource is a database. See here: http://stackoverflow.com/questions/13912489/read-only-access-only-for-sqlite3-from-multiple-threads – Fabian May 22 '15 at 05:32
  • 1
    Maybe the critical issue is whether the performance will be affected even the read only is thread safe. Say 100 threads are reading from a vector of 10000 elements from multiple random indexes. – Kemin Zhou Jul 31 '17 at 23:42

4 Answers4

27

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.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
13

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

ThomasMcLeod
  • 7,603
  • 4
  • 42
  • 80
4

Yes, that's fine.

You shouldn't have any problem.

Paul Nathan
  • 39,638
  • 28
  • 112
  • 212
3

If the data is fixed before any of the reading threads start, then yes, it's OK.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186