我试图找到一种方法来安全删除我的资源和我的互斥锁,确实没有竞争条件。有人能告诉我这段代码是否合适?
struct Resource
{
std::string m_resource;
};
struct Mutex
{
std::mutex* m_mutex;
};
std::map<unsigned int, Resource> myResources;
std::map<unsigned int, std::mutex*> myMutexes;
void shutdown(int UUID)
{
{
boost::lock_guard<boost::mutex> guard(*myMutexes[UUID]);
myResources.erase(UUID);
}
// No need anymore this mutex, because associated resource is deleted
delete myMutexes[UUID];
myMutexes.erase(UUID);
}
void onRecognize(int UUID)
{
boost::lock_guard<boost::mutex> guard(*myMutexes[UUID]);
if (myResources.find(UUID) != myResources.end() )
{
// Do something
}
}
int main()
{
myResources[1] = "resA";
myMutexes[1] = new std::mutex();
std::thread t1(shutdown);
std::thread t2(onRecognize);
t1.join();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
t2.join();
}
那么,我在 shutdown 函数中处理我的互斥锁是否安全?或者在 onRecognize 函数中到达 lock_guard 之前,我的互斥锁仍有可能被删除?
我的最终目标是我只想锁定一个资源。
所以,在以下电话中
shutdown(2);
onRecognize(1);
onRecognize 不需要在 shutdown 之后等待,因为他不能在同一资源上工作。