本文介绍了如何在DLLMain中启动线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在DLLMain中启动线程意味着从根本上说std :: thread。 No表示WinApi,STL表示。当我在流中运行该函数时,我崩溃了,因此从该DLL中调用了该应用程序。

How can I start a thread in DLLMain means std :: thread - fundamentally. No means WinApi, and STL means. When I run the function in the flow, then I crash the application is called from this DLL. Thank you in advance.

此代码获取文件(exe)上的哈希值并将其写入文件。 (* 。文本)。但是应用程序崩溃了

This code gets the hash sum on the file (exe) and writes it to a file. (* .txt). But the application crash

void initialize()
{
    string buffer;
    thread t(calclulateHash, ref(buffer));
    t.detach();
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
        {
            initialize();
            break;
        }
    }
    return true;
}


推荐答案

DllMain( )。

There are limitations on DllMain().

您不应在DllMain中进行任何阻止调用,因为它是从OS加载程序调用的。锁定加载程序可能会阻止某些线程启动,并且通常会导致不良后果。任何形式的锁定。如果您试图获取当前需要OS加载程序锁的线程所持有的锁(从执行该线程时正在持有该锁),则在最佳情况下会死锁。不允许启动线程,因为启动线程时..您可以通过OS加载程序再次调用此DllMain,但现在使用DLL_THREAD_ATTACH参数。

You shouldn't do any blocking calls in DllMain, because it is called from OS loader. Locking loader may prevent some thread to start and in general leads to bad things. Locking of any kind. If you are trying to acquire a lock that is currently held by a thread that needs OS loader lock (which you are being holding while executed from it), you’ll deadlock in best case scenario. Starting threads isn't allowed, because when you start thread.. you call this DllMain again through OS loader, but with DLL_THREAD_ATTACH parameter now. It leads to the same deadlock or illegal concurrent access to uninitialized memory of this module.

明确禁止调用LoadLibrary / LoadLibraryEx,因为这需要操作系统加载程序锁定,这将导致相同的死锁或非法并发访问该模块的未初始化内存。其他对kernel32的调用也可以,您不能对User32进行调用。而且,不要使用CRT内存管理(除非您是静态链接的),否则所有调用动态C运行时的东西都应该使用HeapAlloc和类似的API。否则,将导致调用SxS运行时库。您也无法阅读注册表。任何跨二进制调用都是UB,您调用的二进制文件可能尚未初始化或尚未使用。

Calls to LoadLibrary/LoadLibraryEx are explicitly prohibited, because that requires OS loader lock. Other calls into kernel32 are fine, you can’t call into User32. And don’t use CRT memory management (unless you are linked statically), anything that calls to dynamic C runtime at all – use HeapAlloc and similar API instead. You'll cause call to SxS runtime library otherwise. You can't read the registry either. Any cross-binary calls are UB, the binary you've called into may not have been initialized or have already been unutilized.

祝您有美好的一天。

这篇关于如何在DLLMain中启动线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:23