使用pthreads优雅地退出主线程
Gracefully exiting a main thread with pthreads
我目前正在上一门课,学习线程同步。任务要求我们首先实现一个基于pthreads的简单线程库。他们向我们提供了以下头文件,并告诉我们不应该以任何方式修改它:
#include <pthread.h>
#include <cstring>
class Task {
protected:
/* -- NAME */
static const int MAX_NAME_LEN = 15;
char name[MAX_NAME_LEN];
/* -- IMPLEMENTATION */
pthread_t thread_id;
/* If you implement tasks using pthread, you may need to store
the thread_id of the thread associated with this task.
*/
public:
/* -- CONSTRUCTOR/DESTRUCTOR */
Task(const char _name[]) {
/* Create, initialize the new task. The task is started
with a separate invocation of the Start() method. */
std::strncpy(name, _name, MAX_NAME_LEN);
}
~Task();
/* -- ACCESSORS */
char * Name();
/* Return the name of the task. */
/* -- TASK LAUNCH */
virtual void Start();
/* This method is used to start the thread. For basic tasks
implemented using pthreads, this is where the thread is
created and started. For schedulable tasks (derived from
class Task) this is where the thread is created and handed
over to the scheduler for execution. The functionality of
the task is defined in "Run()"; see below. This method is
called in the constructor of Task.
*/
/* -- TASK FUNCTIONALITY */
//make a thread here
virtual void Run() = 0;
/* The method that is executed when the task object is
started. When the method returns, the thread can be
terminated. The method returns 0 if no error. */
/* -- MAIN THREAD TERMINATION */
static void GracefullyExitMainThread();
/* This function is called at the end of the main() function.
Depending on the particular thread implementation, we have
to make sure that the main thread (i.e., the thread that
runs executes the main function) either waits until all
other threads are done or exits in a way that does not
terminate them.
*/
};
我的问题是关于GracefullyExitMainThread()
函数的。有人告诉我,我需要在它的实现中使用pthread_join()
,但当它是一个类方法时,我不知道如何将线程id传递给它。此外,我本以为它们会在头中包含某种数组或其他结构,以跟踪创建的所有线程。
如果我的帖子很难理解或阅读,很抱歉。我仍在学习C++的所有细微差别,这是我在stackoverflow上的第一篇文章。非常感谢您的帮助。
一种解决方案是在类中存储pthread_ids的静态std::vector(也称为可调整大小的数组)。然后,每当启动线程时,它都会将自己的pthread_id添加到std::向量中。
一旦线程死了,您也可以删除pthread_id,但我确信pthread_join可以正确处理死线程,因此没有必要。
因此,您现在有了一个静态成员中已启动的所有线程的列表,这些线程可用于您的静态函数。只需在列表上循环,然后加入所有列表。
也许你应该读一下这篇文章,它有一个关于如何连接线程的例子
https://computing.llnl.gov/tutorials/pthreads/
如果你也读过这篇文章,你会看到一个描述"join"对线程的实际作用,以及为什么不需要创建一个列表来跟踪所有线程:-)
https://computing.llnl.gov/tutorials/pthreads/man/pthread_join.txt
相关文章:
- std::async 如果线程是从 DLL 创建的,则会阻止进程退出?
- 在线程退出之前,线程分配的内存块是否与线程本身具有相同的相关性?
- STD ::线程不会退出
- C++线程退出循环条件
- gdb 中的线程 0x7fffc57fa700 (LWP 31671) 退出] 是什么意思?
- 如何使用工作线程正确退出Qt应用程序
- Boost.Asio:由于线程退出或应用程序请求,I/O 操作已中止
- 当子线程退出时,如何通知父线程
- 线程已退出,代码为 1:Join() 和 Detach()
- 安全地退出程序 Win32 C++从分离的 std::线程
- 在另一个线程正在运行的情况下退出应用程序时出错
- C++提升线程组.interrupt_all()导致主线程也退出
- 确定线程是否已退出
- 在退出应用程序时安全退出Qt线程
- c++允许后台线程在退出应用程序之前完成
- 如果线程在调用pthread_join之前退出,该怎么办
- JNI - Java 在本机线程完成执行之前退出
- 线程退出时通知Waiters
- 多线程Qt应用程序在退出时不会停止
- 如何以线程安全的方式退出 C++03 中的程序