Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a std::thread to detach and terminate itself

I am currently developing a basic thread pool. I used c++11's std::thread, along with std::condition_variable, and std::unique_lock. It seems to work, and I now would like to be able to kill some threads when too many of them are inactive. For now, their jobs are given through a std::queue of boost::functions. I was thinking of adding a bunch of empty boost::functions so the threads know they have to exit their loop. The thread's loop is like this:

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 detach the thread once I exited the loop. Would it be clean to look for the thread's handle (I have access to a std::list<std::thread*>, and can compare their ids with std::this_thread::get_id()), and is it safe to call detach() from the thread itself, or even join()?

like image 832
Jukurrpa Avatar asked Feb 02 '12 18:02

Jukurrpa


People also ask

How do you detach a thread in C++?

std::thread::detach. Separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits. After calling detach *this no longer owns any thread.

How do you stop a detached thread?

In C++, once the thread is detached or uses the detach() function, then we cannot stop such threads, and still, if there is a need for stopping such threads, then only one way is to return the thread from the initial thread function by instantiating it in main() function, adding the Boolean value but before exiting ...

What happens to 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.

Does exit terminate all threads?

Calling the exit subroutine terminates the entire process, including all its threads. In a multithreaded program, the exit subroutine should only be used when the entire process needs to be terminated; for example, in the case of an unrecoverable error.


1 Answers

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

But you cannot call join() from the thread itself: an attempt for a thread to join with itself would result in a deadlock, and C++11 implementations should recognize that and throw system_error with the error condition of resource_deadlock_would_occur.

Alternatively, you can leave a message (e.g. via an std::atomic variable) to the main thread that the thread associated with a particular instance of std::thread is about to complete its execution, and let the main thread join with this instance at a later point.

like image 139
Alexey Kukanov Avatar answered Sep 20 '22 13:09

Alexey Kukanov