Is it possible to use mutex to lock an element in a vector not the whole vector ?
For example, given a vector myVec; push back 10 elements into 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 multiple threads. How to use mutex to lock only one buffer in myVec such that one thread can write or read an element ; another can read and write another element at the same time ?
thanks
What you want is both simpler and more difficult than you think:
If your container as a whole is unchanged, i.e. there are no insertions or erases, then the standard library containers already offer a limited type of thread safety, which is that different threads are allowed to read or modify different container elements, i.e. as long as no more than one thread accesses any given element.
On the other hand, if the container is modified as a whole, then you have almost no safeties at all: Depending on the type of container, you absolutely must understand reference and iterator invalidation. If you know that references or iterators to an element are unaffected, then the above applies (respectively to the reference or the dereferenced iterator). If not, then you have no hope of doing anything other than reacquiring a new reference to the desired element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With