我需要为每个将通过宏访问的线程存储一个唯一的指针。我以为我应该用单例和静态thread_local std :: unique_ptr对象来解决这个问题。下面是代码的简化版本:C++ 11:GCC 4.8 static thread_local std :: unique_ptr undefined reference
的main.cpp
#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;
}
yay.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
yay.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
我希望我可以得到铛的更多信息,但它的工作原理与铛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 obj学分?它适用于简单类型,如int或“裸”指针。
编辑:
这是可能的,这是关系到http://gcc.gnu.org/bugzilla/show_bug.cgi?id=55800
EDIT2了一个错误:
解决方法1:编译一个文件,铛(yay.cpp)
解决方法2(可怕和不可移植):首先编译yay.cpp程序集,然后添加
.globl _ZTWN3Yay3yayE
_ZTWN3Yay3yayE = __tls_init
的汇编文件,编译成目标文件,链接,其余
'getYay()'的预处理器替换是否可能会让您感到困惑? – Tom
不,如果我直接删除#define并调用Yay :: getYay(),它不起作用。 – linedot
在您的错误报告中,您会看到代码的简化版本以及可能的解决方法。也许你可以把它作为答案。 –