简体   繁体   中英

pthread_exit usage during stopping the thread

I am creating a thread like

pthread_create(&mon_thread, NULL, &ClassA::m_thread, this);

which runs the following function

void* ClassA::m_thread(void *arg){

  while (!halt_tx) {
  .....}
}

during the stopping I set halt_tx = 1 and let the thread reached to the end of function and in the destructor I call join function

ClassA::~ClassA()
{
   pthread_join(monitor_thread, NULL);
}

My question is whether I should also call pthread_exit(NULL) while stopping the thread.

No.

When the ClassA::m_thread function ends, there's an implicit call to pthread_exit with the function's return value as the thread exit status.

Make sure to have a proper return statement though.

The man page for pthread_exit says:

 Performing a return from the start function of any thread other than the main thread results in an implicit call to pthread_exit()

Creating threads is very resource intensive for the machine. It's a bad idea to create threads implicitly in a class without at least the name of the class making thread creation very clear. For a project I'm working on, I have a ConsumerThread class that is inherited by classes that want to be a consumer, which starts a thread AND sets up a queue. A developer doesn't get to instantiate a class called ConsumerThread and then be surprised when a thread is created. However, a developer could create ClassA and not know a thread was created. Even when writing test code, I'm very careful to make sure thread creation is obvious by virtue of the class name in case the class leaks into production during a moment of weakness.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM