If the vector is initialized at startup, it looks like a fixed-size array, so there is no need to block it. I would prefer an array at this point :) assigned to the new [] if you want.
If, say, threadN, access is only to the N field, then there is no need for blocking, blocking is required when several threads try to gain read and write access to the same resource.
If one stream has access to only one resource for reading and writing and no other stream is available to this resource, there is no problem! You do not need a lock.
If access to one resource is performed between several threads only in readonly mode, you do not need a lock.
And if that was unclear, in your case array[i]
is the read / write resource, and array
is the readonly shared resource.
If you need to synchronize each element, you need a mutex for each element. If there are n resources accessed by m threads, you need to block resources using n mutexes. They are not expensive.
If you have too many resources, you can block parts of the array: one mutex will make your application single-threaded, but you can assign 1 mutex every 10 elements, for example. This way you reduce the number of mutexes, but at the same time you guarantee that not too many threads are not stalled together.
source share