繁体   English   中英

使用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的第一篇文章。 任何帮助是极大的赞赏。

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

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

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

也许您应该阅读此书,其中有一个有关如何加入线程的示例

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

如果您还阅读了此内容,则将看到一个说明,说明“ join”实际上对线程有什么作用,以及为什么不需要创建列表来跟踪所有线程:-)

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

暂无
暂无

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

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