How to check if a std::thread is still running?

If you are willing to make use of C++11 std::async and std::future for running your tasks, then you can utilize the wait_for function of std::future to check if the thread is still running in a neat way like this: #include <future> #include <thread> #include <chrono> #include <iostream> int main() { using namespace std::chrono_literals; /* Run … 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

What happens to a detached thread when main() exits?

The answer to the original question “what happens to a detached thread when main() exits” is: It continues running (because the standard doesn’t say it is stopped), and that’s well-defined, as long as it touches neither (automatic|thread_local) variables of other threads nor static objects. This appears to be allowed to allow thread managers as static … 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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)