我需要为将通过宏访问的每个线程存储一个唯一指针。我想我应该用一个单例和静态 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
到程序集文件,编译到目标文件,与其余文件链接