c++ - Is std::this_thread::get_id() reliable in VS2013? -


the title says everything:)

#include <thread> #include <cstdio>  int main() {     std::thread threads[2];      (int = 0; < 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());         });     }      (auto& : threads)     {         it.join();     }      return 0; } 

when compiling , running using gcc , clang have (my) expected result, 4 messages 2 different values printed in random order. when using vs2013 have 4 messages (as expected), 4 different values!

am doing wrong here or compiler/ms threading library?

edit: tony d pointed out problem seems considered thread::id int. next code works expected:

#include <thread> #include <cassert>  int main() {     std::thread threads[2];      (int = 0; < 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);         });     }      (auto& : threads)     {         it.join();     }      return 0; } 

you forcing std::thread::id int. use std::cout write standard output instead of printf. , use kind of synchronization object:

std::mutex display_mutex;  int main() {     std::thread threads[2];      (int = 0; < 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";         });     }      (auto& : threads)     {         it.join();     }      return 0; } 

but answer question: yes, std::this_thread::get_id() reliable in vs2013.


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -