pthread_exit停止线程期间的使用情况

pthread_exit usage during stopping the thread

本文关键字:用情 情况 线程 exit pthread      更新时间:2023-10-16

我正在创建一个类似的线程

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

运行以下函数

void* ClassA::m_thread(void *arg){
  while (!halt_tx) {
  .....}
}

在停止期间,我设置 halt_tx = 1 并让线程到达函数的末尾,在析构函数中我调用 join 函数

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

我的问题是我是否应该在停止线程时调用 pthread_exit(NULL)。

No.

ClassA::m_thread 函数结束时,会隐式调用pthread_exit函数的返回值作为线程退出状态。

不过,请确保有适当的退货声明。

pthread_exit的手册页说:

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

创建线程对于计算机来说非常耗费资源。 在类中隐式创建线程是一个坏主意,至少没有类的名称,使线程创建非常清晰。 对于我正在处理的一个项目,我有一个 ConsumerThread 类,该类由想要成为使用者的类继承,它启动一个线程并设置一个队列。 开发人员不会实例化一个名为ConsumerThread的类,然后在创建线程时感到惊讶。 但是,开发人员可以创建 ClassA 并且不知道已创建线程。 即使在编写测试代码时,我也非常小心地确保线程创建是显而易见的,因为类名是显而易见的,以防类在弱点时刻泄漏到生产中。

相关文章: