我正在学习一个我们正在学习线程同步的类。该任务要求我们首先实现一个基于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