使用互斥锁时出错

Ada*_*hns 9 c++ linux posix mutex pthreads

当我尝试制作一个以字符串为键并且pthread_mutex_t为元素的地图时,

    map<string, pthread_mutex_t> connectedClientsMutexes;

    pthread_mutex_t myMutex;//= PTHREAD_MUTEX_INITIALIZER;
    connectedClientsMutexes.insert(pair<string,pthread_mutex_t>(userName,myMutex));
while (1)
    {

    pthread_mutex_lock(&connectedClientsMutexes[userName]); 
     // do something here 
    }
Run Code Online (Sandbox Code Playgroud)

这会产生:

阶段3:pthread_mutex_lock.c:312:__pthread_mutex_lock_full:断言`( - (E))= 3 || "健壮"失败了.

Duc*_*uck 9

复制互斥锁是未定义的.尝试在地图中放置指向互斥锁的指针.

编辑这是未定义行为的本质.有时你会幸运(或似乎),有时你却没有.

而不是地图中多个互斥锁的副本,而是将多个指针放入互斥锁.所以类似于:

map<string, pthread_mutex_t *> connectedClientsMutexes;

connectedClientsMutexes.insert(pair<string,pthread_mutex_t *>(userName, &myMutex));

pthread_mutex_lock(connectedClientsMutexes[userName]);
Run Code Online (Sandbox Code Playgroud)

据推测,您将地图传递给各种线程,因此明智的做法是不在堆栈上分配这些互斥锁,除非您是积极的,否则它们不会超出范围.将它们声明为全局变量或动态分配它们并使用它们进行初始化pthread_mutex_init().