Get std :: thread to disconnect and terminate

I am currently developing a basic thread pool. I used C ++ 11 std::thread along with std::condition_variable and std::unique_lock . This seems to work, and now I want to kill some threads when too many of them are inactive. So far, their jobs are being set via std::queue of boost::function s. I was thinking of adding a few empty boost::function so that the threads know that they should exit the loop. The flow loop is as follows:

 void ThreadPool::threadLoop() { boost::function<void ()> oThreadTask; std::unique_lock<std::mutex> oLock(m_oTaskMutex); while (1) { // m_oCV is a static std::condition_variable // m_oTaskQueue is a static std::queue< boost::function<void ()> > m_oCV.wait(oLock, [](){ return m_oTaskQueue.size(); }); oThreadTask = m_oTaskQueue.front(); m_oTaskQueue.pop(); m_oTaskMutex.unlock(); if (oThreadTask.empty()) break ; oThreadTask(); } // ?? } 

The thing is, I'm not sure how to properly disconnect the thread as soon as I exit the loop. It would be clean to look for a thread handle (I have access to std::list<std::thread*> and I can compare their identifiers with std::this_thread::get_id() ), and is it safe to call detach() from the thread itself or even join()

+8
c ++ multithreading
source share
1 answer

Yes, if you have all the thread objects, you can find one that thread::id is equal to this_thread::get_id() , and you can call detach() on it and destroy the thread object after that (C ++ 11 standard prevents this, and I believe that it is based on common practice). Make sure that no other thread of execution refers to the std::thread instance that was destroyed.

But you cannot call join() from the thread itself: trying to bind the thread to yourself will lead to a deadlock, and C ++ 11 implementations should recognize this and throw a system_error with the error condition resource_deadlock_would_occur .

Alternatively, you can leave a message (for example, via std :: atomic variable) in the main thread, which the thread associated with a particular instance of std::thread is about to complete, and let the main thread connect to this instance at a later point .

+11
source share

All Articles