User Tools

Site Tools


c:c_threads:thread_class

C - C++ Threads - Thread Class

If neither join or detach is called with a std::thread object, then when the main thread terminates, it will result in an exception error.

One approach around this issue to to use a class such as this, which checks if the thread is joinable, and if so will detach it from the main thread.

In this way, no exception error is shown.


#include <iostream>
#include <thread>
 
class ThreadRAII
{
  std::thread & m_thread;
 
public:
  ThreadRAII(std::thread  & threadObj) : m_thread(threadObj)
  {
  }
  ~ThreadRAII()
  {
    // Check if thread is joinable then detach the thread.
    if(m_thread.joinable())
    {
      m_thread.detach();
    }
  }
};
 
 
void thread_function()
{
  for(int i = 0; i < 10000; i++);
    std::cout<<"thread_function Executing"<<std::endl;
}
 
 
int main()
{
  std::thread threadObj(thread_function);
 
  // If we comment this Line, then program will crash.
  ThreadRAII wrapperObj(threadObj);
 
return 0;
}

c/c_threads/thread_class.txt · Last modified: 2021/03/05 17:13 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki