我是否需要在指针向量上使用互斥锁? [英] Do I need a mutex on a vector of pointers?
问题描述
这是我的情况的简化版本:
Here is a simplified version of my situation:
void AppendToVector(std::vector<int>* my_vector) {
for (int i = 0; i < 100; i++) {
my_vector->push_back(i);
}
}
void CreateVectors(const int num_threads) {
std::vector<std::vector<int>* > my_vector_of_pointers(10);
ThreadPool pool(num_threads);
for (for int i = 0; i < 10; i++) {
my_vector_of_pointers[i] = new std::vector<int>();
pool.AddTask(AppendToVector,
&my_vector_of_pointers[i]);
}
}
我的问题是,在使用多个线程运行时,是否需要在AppendToVector中放置互斥锁?我的直觉告诉我,我不必这样做,因为不可能有两个线程访问相同的数据,但是我并不完全有信心.
My question is whether I need to put a mutex lock in AppendToVector when running this with multiple threads? My intuition tells me I do not have to because there is no possibility of two threads accessing the same data, but I am not fully confident.
推荐答案
每个线程都附加不同的std::vector
(在AppendToVector
函数内部),因此无需锁定您的情况.如果您以多个线程访问同一向量的方式更改代码,则需要锁定.不要感到困惑,因为您传递给AppendToVector
的std::vectors
是主std::list
的它们自己的元素,仅重要的是这里的线程正在使用完全不同的(非共享的)内存进行操作
Every thread is appending different std::vector
(inside AppendToVector
function) so there is no need for locking in your case. In case you change your code in the way more than one thread access same vector then you will need lock. Don't be confused because std::vectors
you are passing to AppendToVector
are them-selfs elements of main std::list
, it matters only that here threads are manipulating with completely different (not shared) memory
这篇关于我是否需要在指针向量上使用互斥锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!