Multithreaded reading and writing to :: stl :: vector, a vector resource that is hard to release

I am writing code in VS2005 using its STL. I have one user interface thread to read a vector and a workflow to write to the vector. I use :: boost :: shared_ptr as a vector element.

vector<shared_ptr<Class>> vec;

but I find if I manipulate vec in both threads at the same time (I can guarantee that they do not visit the same area, UI Thread always reads the area in which there is information)

vec.clear () seems unable to free the resource. The problem occurs in shared_ptr, it cannot free its resource.

What is the problem? This is due to the fact that when a vector reaches its order capacity, it is redistributed in memory, then the original part becomes invalid.

As far as I know when redistributing, the iterator will be invalid, why the problem occurred when I used vec [i]. // -----------------------------------------------

What locks are needed? I mean: if the vector element is shared_ptr, when thread A receives the smart_p point, will another thread B wait until A completes the operation on smart_p to the right? Or just add a lock when a thread tries to read a point, when read completion is complete, thread B can continue to do something.

+3
source share
3 answers

When you access the same resource from multiple threads, blocking is required. If you do not, you have all the strange behavior, as you see.

Boost, - Boost.Thread. , , /; shared_mutex Boost.Thread.

, , , undefined - . , !

OP: ( ), ( , ), . mutex .

+4

. , ().

0

It is possible to access a list or an array like this at the same time. However, std :: vector is not a good choice due to its resizing. Correct use requires a fixed-size array or a special lock or copy-update operation when resizing. It also needs independent front and rear pointers with a lock or atomic update.

Another answer mentions message queues. A shared array, as I described, is a common and efficient way to implement them.

0
source

Source: https://habr.com/ru/post/1699201/


All Articles