pthread_mutex_t 的向量为所有互斥锁提供了相同的地址

Vector of pthread_mutex_t gives me the same address for all mutex

我有这个结构:

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

我打印这个的原因是因为我的并发性有问题而且我注意到我没有锁定正确的 Mutex。

所以我的问题是我是否正确地初始化了互斥体以获得 3 个不同的互斥体?我的打印真的在这里显示出问题吗? 从答案中,我正在打印始终相同的堆栈指针。这是否意味着我正在为同一地址初始化互斥体?

您正在打印堆栈变量的地址 mutex,每次循环都会在同一地址重新创建此地址