gpt4 book ai didi

c++ - 使用 pthreads 优雅地退出主线程

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:33:06 26 4
gpt4 key购买 nike

我目前正在上一门学习线程同步的类(class)。作业要求我们首先实现一个基于 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 传递给它。另外,我原以为它们会在 header 中包含某种数组或其他结构,以跟踪所有创建的线程。

如果我的帖子难以理解或阅读,我深表歉意。我仍在学习 C++ 的所有细微差别,这是我关于 stackoverflow 的第一篇文章。非常感谢任何帮助。

最佳答案

一种解决方案是使用静态 std::vector(又名可调整大小的数组)在类中存储 pthread_id。然后,无论何时启动线程,它都会将自己的 pthread_id 添加到 std::vector。

您也可以在线程死亡后删除 pthread_id,但我相当确定 pthread_join 会正确处理死线程,因此没有必要。

因此,您现在拥有一个可用于静态函数的静态成员中已启动的所有线程的列表。只需遍历列表,然后加入所有列表即可。

关于c++ - 使用 pthreads 优雅地退出主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9547231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com