Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreaded, read-only access to a Vector. Copy or lock?

Wondered if I could get your thoughts on what I should do in this scenario.

Assume I have between 4 to 8 threads and I have a vector of values which will never be written to, only read by the threads.

I have the option of creating a copy of the vector for each thread and then no thread locking between the threads, trying to access a shared copy. Or, I could lock one copy of the vector and make all threads access that.

What is the latency of a thread lock, in comparison to copying the vector? How big would the vector have to be, to make the overhead of the lock faster than copying the vector?

like image 646
user997112 Avatar asked May 30 '12 21:05

user997112


People also ask

Is vector read thread safe C++?

YES for the scenario you mention, it is perfectly Thread Safe.

Is read only data thread safe?

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.

Can multiple threads read the same file?

Multiple threads can also read data from the same FITS file simultaneously, as long as the file was opened independently by each thread. This relies on the operating system to correctly deal with reading the same file by multiple processes.

Can we make vector as non Threadsafe?

No. Managing the vector class across threads is not safe, you need to use some synchronization mechanism (e.g. a mutex) to protect read/write access to the std::vector<> instance.


2 Answers

If no thread ever writes to it, you can safely share it without any lock or copy. Data races can only occur if there are write accesses involved.

like image 129
R. Martinho Fernandes Avatar answered Oct 17 '22 05:10

R. Martinho Fernandes


Assuming the vector doesn't change after the threads start accessing it, there is no need to lock it. If the thread that populates the vector finishes populating before the reader threads start reading, you are safe without any further synchronization.

like image 7
juanchopanza Avatar answered Oct 17 '22 07:10

juanchopanza