用pthreads优雅地退出主线程

时间:2012-03-03 15:22:43

标签: c++ 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上的第一篇文章。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

一种解决方案是使用静态std :: vector(AKA是可调整大小的数组),在类中存储pthread_ids。然后,每当启动一个线程时,它就会将自己的pthread_id添加到std :: vector。

一旦线程死掉,你也可以删除pthread_id,但我相当肯定pthread_join正确处理死线程,所以没有必要。

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

答案 1 :(得分:0)

也许你应该阅读这篇文章,它有一个关于如何加入线程的例子

https://computing.llnl.gov/tutorials/pthreads/

如果你也读过这篇文章,你会看到一个描述&#34;加入&#34;实际上与线程有关,为什么不需要创建一个列表来跟踪所有线程: - )

https://computing.llnl.gov/tutorials/pthreads/man/pthread_join.txt