std::thread::join() hangs if called after main() exits when using VS2012 RC

Tracing through Fraser’s sample code in his connect bug (https://connect.microsoft.com/VisualStudio/feedback/details/747145) with VS2012 RTM seems to show a fairly straightforward case of deadlocking. This likely isn’t specific to std::thread – likely _beginthreadex suffers the same fate. What I see in the debugger is the following: On the main thread, the main() function has completed, the process … Read more

I want to kill a std::thread using its thread object? [duplicate]

@bamboon’s answer is good, however I feel this deserves a stronger statement. Whatever the language you use, your program will acquire and release resources: memory, file descriptors, … For simple programs that are fired in one shots, leaking resources does not matter much: when the program ends modern OSes automatically take the resources back; however … Read more

Thread pooling in C++11

This is adapted from my answer to another very similar post. Let’s build a ThreadPool class: class ThreadPool { public: void Start(); void QueueJob(const std::function<void()>& job); void Stop(); void busy(); private: void ThreadLoop(); bool should_terminate = false; // Tells threads to stop looking for jobs std::mutex queue_mutex; // Prevents data races to the job queue … Read more

When should I use std::thread::detach?

In the destructor of std::thread, std::terminate is called if: the thread was not joined (with t.join()) and was not detached either (with t.detach()) Thus, you should always either join or detach a thread before the flows of execution reaches the destructor. When a program terminates (ie, main returns) the remaining detached threads executing in the … Read more

Passing object by reference to std::thread in C++11

Explicitly initialize the thread with a reference_wrapper by using std::ref: auto thread1 = std::thread(SimpleThread, std::ref(a)); (or std::cref instead of std::ref, as appropriate). Per notes from cppreference on std:thread: The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to … Read more