删除被锁定的互斥锁 [英] Deleting a mutex that is locked
问题描述
我有一个程序有多个资源需要被自己的互斥锁。
I have a program with multiple resources that needs to be lock by their own mutex.
在这个程序中,可能会发生, A 被锁定,资源A 在另一个线程中被删除。
In this program, it might happen that while mutex for resource A is locked, resource A is deleted in another thread.
以下代码尝试重现我尝试完成的逻辑:
The following code try to reproduce the logic of what I try to accomplish :
#include <thread>
#include <mutex>
#include <iostream>
#include <map>
int g_i = 0;
struct Resource
{
std::mutex* m_mutex;
};
std::map<unsigned int, Resource> myResources;
std::mutex g_i_mutex; // protects g_i
void shutdown()
{
std::cout << "shutdown -> myMap.size = : " << myResources.size() << std::endl;
std::lock_guard<std::mutex> lock(*myResources[1].m_mutex);
++g_i;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
delete myResources[1].m_mutex;
myResources[1].m_mutex = NULL;
myResources.erase(1);
std::cout << "shutdown -> myMap.size = : " << myResources.size() << std::endl;
std::cout << "shutdown : " << g_i << '\n';
}
void onRecognize()
{
std::cout << "onRecognize -> myMap.size = : " << myResources.size() << std::endl;
std::lock_guard<std::mutex> lock(*myResources[1].m_mutex);
std::cout << "onRecognize -> myMap.size = : " << myResources.size() << std::endl;
++g_i;
std::cout << "onRecognize : " << g_i << '\n';
}
int main()
{
std::cout << __func__ << ": " << g_i << '\n';
Resource myStruct;
myStruct.m_mutex = new std::mutex();
myResources[1] = myStruct;
std::thread t1(shutdown);
std::thread t2(onRecognize);
t1.join();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
t2.join();
std::cout << __func__ << ": " << g_i << '\n';
}
我试过这段代码,但我想知道在 onRecognize 函数中使用 lock_guard 发生了什么,因为互斥体在被锁定时被删除。所以,我的问题可能是:
I tried this snippet of code and it works. But I am wondering what happen with lock_guard in onRecognize function, because the mutex is being deleted while he is locked. So, my question might be :
在他被锁定的地方删除互斥是危险的吗?
Does deleting a mutex while he is locked somewhere else is dangerous?
Thx
推荐答案
在锁定时不要销毁互斥体。
Don't destroy a mutex while it is locked.
如果互斥量由任何线程拥有或者任何线程在持有互斥量的任何所有权时终止,则行为是未定义的。
The behavior is undefined if the mutex is owned by any thread or if any thread terminates while holding any ownership of the mutex.
http://en.cppreference.com/w / cpp / thread / mutex /〜mutex
这篇关于删除被锁定的互斥锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!