You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows DLL中使用ThreadPool遇线程存储时长编译错误求解决方案

在Windows DLL中使用Antoine Savine的ThreadPool遇到的编译问题

背景与代码实现

我在Windows DLL中使用Antoine Savine仓库里的ThreadPool(基于ConcurrentQueue),对应仓库中的threadPool.h头文件与ThreadPool.cpp源文件。

我在新增的dllmain.cpp中实现了DLL入口函数,模仿仓库XLL代码的启动/停止逻辑:

BOOL WINAPI DllMain(
    HINSTANCE hinstDLL,  // handle to DLL module
    DWORD fdwReason,     // reason for calling function
    LPVOID lpvReserved)  // reserved
{
    // Perform actions based on the reason for calling.
    switch (fdwReason)
    {
    case DLL_PROCESS_ATTACH:
        // Initialize once for each new process.
        // Return FALSE to fail DLL load.
        ThreadPool::getInstance()->start(std::thread::hardware_concurrency() - 1);
        break;

    case DLL_THREAD_ATTACH:
        // Do thread-specific initialization.
        break;

    case DLL_THREAD_DETACH:
        // Do thread-specific cleanup.
        break;

    case DLL_PROCESS_DETACH:

        if (lpvReserved != nullptr)
        {
            break; // do not do cleanup if process termination scenario
        }
        // Perform any necessary cleanup.
        ThreadPool::getInstance()->stop();
        break;
    }
    return TRUE;  // Successful DLL_PROCESS_ATTACH.
}

后续在DLL业务代码中使用ThreadPool的逻辑如下:

ThreadPool* pool = ThreadPool::getInstance();
const size_t nThread = pool->numThreads();
// 声明每个线程对应的对象等...然后...
// 为futures预留内存
std::vector<TaskHandle> futures;
futures.reserve(somesizet);
futures.push_back(pool->spawnTask([&, firstPath, pathsInTask]()
{
    // 业务逻辑
}));

这段代码在EXE项目中编译运行完全正常,但在DLL项目中编译时出现问题。

编译错误详情

  • 不导出ThreadPool相关内容时,出现未解析外部符号错误:
unresolved external symbol "private: static class ThreadPool ThreadPool::myInstance" (?myInstance@ThreadPool@@0V1@A)
unresolved external symbol "private: static unsigned __int64 ThreadPool::myTLSNum" (?myTLSNum@ThreadPool@@0_KA)
  • 导出静态成员或ThreadPool类时,出现编译错误:
'private: static unsigned __int64 ThreadPool::myTLSNum': data with thread storage duration may not have dll interface

我了解到线程本地存储的变量无法导出为DLL接口,但疑惑仓库中的XLL(本质是调用Excel C API的C++ DLL)却能正常使用该ThreadPool实现。

我使用的是Microsoft Visual Studio Professional 2022 Version 17.7.5,编译选项为/std:c++-latest。

请求解决方法

请问针对上述问题,有哪些可行的解决方法?


内容的提问来源于stack exchange,提问作者11house

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 16:44:53