【发布时间】:2017-05-26 14:12:24
【问题描述】:
我有这个结构:
struct thread_items {
pthread_mutex_t mutex;
int i;
thread_items(pthread_mutex_t m, int i): mutex(m), i(i){}
}
我正在尝试创建这个结构的数组并在我使用它时初始化所有互斥锁。出于某种原因,当我打印互斥体地址时,我得到所有互斥体的地址相同:
vector <thread_items*> thread_items_vec;
for (int i = 0; i < 3; i++)
{
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
thread_items * items = new thread_items(mutex, i);
thread_items_vec.push_back(items);
cout << "Mutex " << i << " is " << &mutex << endl;
}
此打印结果如下:
Mutex 0 is 0x7fff9580b520
Mutex 1 is 0x7fff9580b520
Mutex 2 is 0x7fff9580b520
我之所以打印这个是因为我的并发性有问题,而且我注意到我没有锁定正确的互斥锁。
所以我的问题是我是否正确初始化互斥锁以获得 3 个不同的互斥锁?我的打印在这里真的有问题吗? 从答案中,我正在打印始终相同的堆栈指针。这是否意味着我正在为同一个地址初始化我的 Mutex?
【问题讨论】:
-
什么是
thread_items_map? -
什么是thread_items_map?
-
您显示
thread_items和vector <thread_items>,然后创建一个thread_items_map*并将其添加到向量中。请阅读stackoverflow.com/help/on-topic尤其是How to create a Minimal, Complete, and Verifiable example。 -
在 C++11 中最好使用
std::mutex而不是pthread_mutex_t -
不,您没有修复它,因为您将
thread_items*推入vector<thread_items>。我再说一遍,请阅读How to create a Minimal, Complete, and Verifiable example