Is it possible to use a mutex to block an element with a vector, and not with the whole vector?

Is it possible to use a mutex to block an element in a vector, and not the entire vector?

For example, if the vector myVec is specified; drop 10 items in myVec

for (int i = 0; i < 10; ++i) { buffer myBuf = i; // actually myBuf is not necessarily int. myVec.push_back(myBuf); } 

Each element of the vector will be changed asynchronously by several threads. How to use a mutex to lock only one buffer in myVec so that one thread can write or read an element; can another read and write another element at the same time?

thanks

+4
source share
2 answers

What you want is simpler and more complex than you think:

If your container as a whole does not change, i.e. there are no inserts or deletions, then the standard library containers already offer a limited type of thread safety, which means that other threads are allowed to read or modify various elements of the container, i.e. if no more than one thread accesses any given element.

On the other hand, if the container is changed as a whole, then you have practically no security: depending on the type of container, you absolutely must understand the invalidity of links and iterators. If , you know, that references or iterators to an element are not affected, then the above applies (respectively, to a reference or dereferenced iterator). If not, then you have no hope of doing anything else than to re-find a new link to the desired item.

+4
source

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.

+2
source

All Articles