C ++从多个线程访问向量 [英] C++ Access to vector from multiple threads
问题描述
在我的程序中,一些线程正在运行.每个线程都获得一个指向某个对象的指针(在我的程序中为vector).然后每个线程都会修改向量.
In my program I've some threads running. Each thread gets a pointer to some object (in my program - vector). And each thread modifies the vector.
有时我的程序会因段错误而失败.我以为是因为线程A开始对向量做一些操作而线程B还没有完成对它的操作?会不会是真的?
And sometimes my program fails with a segm-fault. I thought it occurred because thread A begins doing something with the vector while thread B hasn't finished operating with it? Can it bee true?
我应该如何解决?线程同步?还是制作一个标志VectorIsInUse
并在操作它时将该标志设置为true?
How am I supposed to fix it? Thread synchronization? Or maybe make a flag VectorIsInUse
and set this flag to true while operating with it?
推荐答案
vector
也不是线程安全的.您必须自己明确管理同步. std::mutex
或
vector
, like all STL containers, is not thread-safe. You have to explicitly manage the synchronization yourself. A std::mutex
or boost::mutex
could be use to synchronize access to the vector
.
请勿使用标志,因为它不是线程安全的:
Do not use a flag as this is not thread-safe:
- 线程A检查
isInUse
标志的值,它是false
- 线程A被挂起
- 线程B检查
isInUse
标志的值,它是false
- 线程B将
isInUse
设置为true
- 线程B被暂停
- 线程A已恢复
- 线程A仍然认为
isInUse
是false
并将其设置为true
- 线程A和线程B现在都可以访问
vector
- Thread A checks value of
isInUse
flag and it isfalse
- Thread A is suspended
- Thread B checks value of
isInUse
flag and it isfalse
- Thread B sets
isInUse
totrue
- Thread B is suspended
- Thread A is resumed
- Thread A still thinks
isInUse
isfalse
and sets ittrue
- Thread A and Thread B now both have access to the
vector
请注意,每个线程都必须在使用整个时间期间锁定vector
.这包括修改vector
并使用vector
的迭代器,因为如果迭代器所引用的元素为erase()
或vector
进行内部重新分配,则迭代器可能变得无效.例如,不要:
Note that each thread will have to lock the vector
for the entire time it needs to use it. This includes modifying the vector
and using the vector
's iterators as iterators can become invalidated if the element they refer to is erase()
or the vector
undergoes an internal reallocation. For example do not:
mtx.lock();
std::vector<std::string>::iterator i = the_vector.begin();
mtx.unlock();
// 'i' can become invalid if the `vector` is modified.
这篇关于C ++从多个线程访问向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!