简体   繁体   English

停止线程期间的pthread_exit用法

[英]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 在停止期间,我设置halt_tx = 1并让线程到达函数的末尾,在析构函数中,我调用join函数

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

My question is whether I should also call pthread_exit(NULL) while stopping the thread. 我的问题是在停止线程时是否还应该调用pthread_exit(NULL)。

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. ClassA::m_thread函数结束时,将使用函数的返回值作为线程退出状态对pthread_exit进行隐式调用。

Make sure to have a proper return statement though. 但是请确保有正确的return语句。

The man page for pthread_exit says: 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()

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. 对于我正在处理的项目,我有一个ConsumerThread类,该类由想要成为使用者的类继承,该类将启动线程并设置队列。 A developer doesn't get to instantiate a class called ConsumerThread and then be surprised when a thread is created. 开发人员不会实例化一个名为ConsumerThread的类,然后在创建线程时会感到惊讶。 However, a developer could create ClassA and not know a thread was created. 但是,开发人员可以创建ClassA并且不知道创建了线程。 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. 即使在编写测试代码时,我也要非常小心,以确保借助类名可以明显地创建线程,以防在弱点时该类泄漏到生产环境中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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