15

我需要为将通过宏访问的每个线程存储一个唯一指针。我想我应该用一个单例和静态 thread_local std::unique_ptr 对象来解决这个问题。这是代码的简化版本:

主文件

#include <thread>
#include <vector>
#include <iostream>
#include <mutex>
using namespace std;

#include "yay.hpp"

mutex coutMutex;

void yay(int id)
{
    int* yayPtr = getYay();

    // I know this is bad
    coutMutex.lock();
    cout << "Yay nr. " << id << " address: " << yayPtr << endl;
    coutMutex.unlock();
}

int main()
{
    vector<thread> happy;
    for(int i = 0; i < thread::hardware_concurrency(); i++)
    {
        happy.push_back(thread(yay, i));
    }

    for(auto& smile : happy)
    {
        smile.join();
    }
    return 0;
}

耶.hpp

#ifndef BE_HAPPY
#define BE_HAPPY

#include <memory>
class Yay
{
    private:
        static thread_local std::unique_ptr<int> yay;
        Yay() = delete;
        Yay(const Yay&) = delete;
        ~Yay() {}
    public:
        static int* getYay()
        {
            if(!yay.get())
            {
                yay.reset(new int);
            }
            return yay.get();
        }
};

#define getYay() Yay::getYay()

#endif

耶.cpp

#include "yay.hpp"

thread_local std::unique_ptr<int>  Yay::yay = nullptr;

如果我用 gcc 4.8.1 编译它:

g++ -std=c++11 -pthread -o yay main.cpp yay.cpp

我得到:

/tmp/cceSigGT.o: In function `_ZTWN3Yay3yayE':
main.cpp:(.text._ZTWN3Yay3yayE[_ZTWN3Yay3yayE]+0x5): undefined reference to `_ZTHN3Yay3yayE'
collect2: error: ld returned 1 exit status

我希望我可以从 clang 获得更多信息,但是它与 clang 3.4 完美配合:

clang++ -std=c++11 -pthread -o yay main.cpp yay.cpp

运行程序会产生我期望的结果:

Yay nr. 2 address: 0x7fcd780008e0
Yay nr. 0 address: 0x7fcd880008e0
Yay nr. 1 address: 0x7fcd800008e0
Yay nr. 3 address: 0x7fcd700008e0
Yay nr. 4 address: 0x7fcd740008e0
Yay nr. 5 address: 0x7fcd680008e0
Yay nr. 6 address: 0x7fcd6c0008e0
Yay nr. 7 address: 0x7fcd600008e0

我不确定我在这里做错了什么,不可能有静态 thread_local unique_ptr 对象吗?它适用于简单类型,如 int 或“裸”指针。

编辑:

这可能是与http://gcc.gnu.org/bugzilla/show_bug.cgi?id=55800相关的错误

编辑2:

解决方法 1:使用 clang (yay.cpp) 编译一个文件

解决方法 2(可怕且不可移植):首先将 yay.cpp 编译为程序集,添加

.globl _ZTWN3Yay3yayE
_ZTWN3Yay3yayE = __tls_init

到程序集文件,编译到目标文件,与其余文件链接

4

2 回答 2

3

我通过在 Yay.hpp 中为 Yay 定义一个无操作的 ctor 来对此进行实验:

- 耶()=删除;
+耶(){}

当我这样做时,错误消息变为:

/tmp/cc8gDxIg.o:在函数“Yay::yay 的 TLS 包装函数”中:
main.cpp:(.text._ZTWN3Yay3yayE[_ZTWN3Yay3yayE]+0x5): 未定义对 Yay::yay 的 TLS 初始化函数的引用

这导致我发现GCC bug 55800。该错误存在于 4.8.2 之前的 GCC 版本中,并在 4.8.3 和 4.9 中得到修复。在我在重复的GCC 错误 59364上发现的讨论线程中,已决定不向后移植该修复程序。因此,在您迁移到 4.9 之前,您的 assembler hack 似乎是唯一可用的解决方案。

于 2014-03-20T16:57:21.197 回答
1

对我来说,事实证明我正在链接-Wl,--image-base,0x14000000并删除它或将其更改为-Wl,--image-base,0x10000000并且问题消失了。不知道这里到底发生了什么......

我相信我遇到了 gcc 错误64697,因为它确实是一个静态 thread_local -std=c++11。它工作在 32 位,但不是 64?很奇怪... gcc 8.2.0 mingw w64 交叉编译:

 librtmfp.a(IOSocket.o):IOSocket.cpp:(.text+0x46c4): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `TLS init function for Base::ThreadQueue::_PCurrent'

原始提示在这里

于 2018-11-01T04:27:38.400 回答