簡體   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