在VS2013中std :: this_thread :: get_id()是否可靠?

时间:2014-03-06 10:11:44

标签: c++ multithreading c++11 visual-studio-2013

标题说明了一切:)

#include <thread>
#include <cstdio>

int main()
{
    std::thread threads[2];

    for (int i = 0; i < 2; ++i)
    {
        threads[i] = std::thread([&]()
        {
            printf("thread id = %x\n", std::this_thread::get_id());
            printf("thread id = %x\n", std::this_thread::get_id());
        });
    }

    for (auto& it : threads)
    {
        it.join();
    }

    return 0;
}

当使用GCC和Clang编译并运行它时,我有(我的)预期结果,有4个消息,其中2个不同的值以某种随机顺序打印。当使用VS2013时,我有4条消息(如预期的那样),但有4个不同的值!

我在这里做错了什么或编译器/ MS线程库?

编辑:正如Tony D所指出的那样,问题似乎是我认为thread :: id是一个int。下一个代码按预期工作:

#include <thread>
#include <cassert>

int main()
{
    std::thread threads[2];

    for (int i = 0; i < 2; ++i)
    {
        threads[i] = std::thread([&]()
        {
            std::thread::id id1 = std::this_thread::get_id();
            std::thread::id id2 = std::this_thread::get_id();
            assert(id1 == id2);
        });
    }

    for (auto& it : threads)
    {
        it.join();
    }

    return 0;
}

1 个答案:

答案 0 :(得分:4)

您迫使std::thread::id加入int。使用std::cout写入标准输出而不是printf。并使用某种同步对象:

std::mutex display_mutex;

int main()
{
    std::thread threads[2];

    for (int i = 0; i < 2; ++i)
    {
        threads[i] = std::thread([&]()
        {
            std::unique_lock<std::mutex> display_lock(display_mutex);
            std::cout << "thread id = " << std::this_thread::get_id() << "\n";
            std::cout << "thread id = " << std::this_thread::get_id() << "\n";
        });
    }

    for (auto& it : threads)
    {
        it.join();
    }

    return 0;
}

但回答你的问题:是的,std::this_thread::get_id()在VS2013中非常可靠。