gpt4 book ai didi

c++ - 删除锁定的互斥量

转载 作者:搜寻专家 更新时间:2023-10-31 01:37:32 29 4
gpt4 key购买 nike

我有一个包含多个资源的程序,需要用它们自己的互斥锁来锁定。

在这个程序中,可能会发生这样的情况,当资源A的互斥锁被锁定时,资源A在另一个线程中被删除。

下面的代码试图重现我试图完成的逻辑:

#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 会发生什么,因为互斥量在他被锁定时被删除。所以,我的问题可能是:

在他被锁定在别处时删除互斥锁是否危险?

谢谢

最佳答案

不要在锁定时销毁互斥锁​​。

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

关于c++ - 删除锁定的互斥量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34030156/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com