在静态库中存储线程ID的正确方法

时间:2019-02-11 07:42:27

标签: c++ multithreading static-libraries

我正在开发一个多线程项目,出于各种原因需要主线程的ID。 这是执行此操作的正确方法吗?

//this is in the static library
std::thread::id * FMainThreadID;

//this is in the static library
std::thread::id MainThreadID()
{
    return *FMainThreadID;
}

//this also is in the static library
void InitializeStaticLibrary()
{
    FMainThreadID = &std::this_thread::get_id();
}

int main()
{
    //beginning of the program
    InitializeStaticLibrary();


    //...

    if (MainThreadID() == std::this_thread::get_id())
        std::cout << "This is the main thread\n";
    else
        std::cout << "This is NOT the main thread\n";
}

谢谢。

1 个答案:

答案 0 :(得分:2)

几乎正确。您必须存储实际的线程ID,而不是指向它的指针。像这样:

//this is in the static library
std::thread::id FMainThreadID;

//this is in the static library
std::thread::id GetMainThreadID()
{
    return FMainThreadID;
}

//this also is in the static library
void InitializeStaticLibrary()
{
    FMainThreadID = std::this_thread::get_id();
}

int main()
{
    //beginning of the program
    InitializeStaticLibrary();


    //...

    if (GetMainThreadID() == std::this_thread::get_id())
        std::cout << "This is the main thread\n";
    else
        std::cout << "This is NOT the main thread\n";
}

我认为您的原始代码保存了一个指向临时对象的指针,然后掉了下来。通常,获取返回值的地址不是一个好主意,因为这些值通常是堆栈上的临时值。