无法在DLL上锁定c ++ 11 std :: mutex [英] Cannot lock a c++ 11 std::mutex on a DLL

查看:239
本文介绍了无法在DLL上锁定c ++ 11 std :: mutex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用std :: lock对象来阻止对DLL初始化函数的多次调用。

I'm trying to prevent multiple calls to a DLL initialization function by using a std::lock object.

在独立使用这样的程序程序工作:

While using a program like this on a stand alone program works:

#include <mutex>
std::mutex mtx;

void main(){
  mtx.lock();
  (...)
  mtx.unlock()
}

这个完全相同的代码在DLL上调用时无法通过 mtx.lock()

This exact same code cannot get past the mtx.lock() when called on a DLL.

BOOL APIENTRY DllMain(HANDLE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved)
{
    f_Init(VERSION_ID);
    return TRUE;
}

//On another cpp file, a static library actually.
#include <mutex>
std::mutex mutex_state;
void f_Init(DWORD version){
    //Acquire the state lock
    mutex_state.lock(); //<-- Will NOT get past this line
    (...)
    mutex_state.unlock();
}

为什么在这种情况下锁定互斥锁不可能?

Why is it imposible to lock the mutex on this situation?

我目前正在使用Microsoft Visual Studio 2013.

I'm currently using Microsoft Visual Studio 2013.

推荐答案

互斥需要。对 DllMain 的访问由实现序列化。

The mutex is not needed. Access to DllMain is serialized by the implementation.


访问入口点由系统在过程范围内序列化。 DllMain中的线程持有加载器锁,因此不能动态加载或初始化额外的DLL。 - DllMain Entry Point a>

输入 DllMain 时,您的代码会导致死锁锁。试图获取额外的锁,同时持有一些未知的锁组合是非常,非常可能是死锁。您应该从未获取 DllMain 内的任何其他锁。

Your code deadlocks deadlock when you enter DllMain because you already hold locks. Trying to acquire additional locks while holding some unknown combination of locks is very, very likely to deadlock. You should never acquire any additional locks inside DllMain.

如果需要附加一些额外的DLL来锁定互斥体。两个DLL不能同时附加,并且您的DLL正在附加。首次锁定互斥可能需要分配内存,并且分配内存可能需要附加DLL - 所以不要在DllMain中这样做。

Consider, for example, if some additional DLL needs to be attached to lock the mutex. Two DLL's cannot be attached at the same time, and your DLL is being attached. Locking a mutex for the first time may require allocating memory and allocating memory may require attaching DLL's -- so don't do that in DllMain.

顺便说一句,痛苦的限制适用于全局对象的构造函数和析构函数。

By the way, these same painful restrictions apply to constructors and destructors for global objects.

这篇关于无法在DLL上锁定c ++ 11 std :: mutex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆