我正在學習一個我們正在學習線程同步的類。該任務要求我們首先實現一個基於pthread的簡單線程庫。他們與下面的頭文件提供給我們,並告訴我們,我們沒有必要對其進行修改以任何方式:用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上的第一篇文章。任何幫助是極大的讚賞。
有一個‘或’GracefullyExitMainThread的定義,這使得它不可能實現。選一個。 – stark 2012-03-03 15:25:34
一般而言,你不想在頭文件中聲明變量;您直接在.c或.cpp文件中執行此操作。頭文件包含_other_源文件需要了解的函數和變量的聲明。 – 2012-03-03 15:35:26
@AdamLiss他聲明瞭什麼額外的變量? – Lalaland 2012-03-03 15:39:01