|
Threads-Devel : |
Subject: Re: [Threads-devel] Concurrent vector assignment
From: Anthony Williams (anthony_at_[hidden])
Date: 2012-01-03 05:04:26
On 26/12/11 11:38, David White wrote:
> I have a vector of objects which I would like to process concurrently. Through the use of a thread-safe queue, I can guarantee that only one thread will work on any one vector element at a time. Hence, each element is modified once by a single thread via iterators.
>
> My question is - do I need a mutex and associated locking for this vector assignment behaviour? In other words, does each thread need to lock the vector before it can modify an element in which no other thread is interested in?
If you do not modify the vector itself, then no locking is required for
accessing the elements unless the same element can be accessed by
multiple threads concurrently. Each vector element is a discrete object,
and therefore if thread A accesses element vec[0] and thread B accesses
vec[1] then no synchronization is required. If both threads access
vec[0] then you will need to ensure that this is safe, just as if both
threads accessed the same object that was not stored in a vector.
Modifying the vector itself (e.g. with reserve(), push_back(), insert(),
erase(), etc.) requires that all threads that may attempt to access the
vector concurrently with the modification use the same lock.
Anthony
-- Author of C++ Concurrency in Action http://www.stdthread.co.uk/book/ just::thread C++0x thread library http://www.stdthread.co.uk Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk 15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976