현재 스레드 동기화에 대해 배우는 클래스를 만들고 있습니다. 이 과제는 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
일반적으로 헤더 파일에 변수를 선언하고 싶지는 않습니다. .c 또는 .cpp 파일에서 직접 그렇게합니다. 헤더에는 _other_ 소스 파일에 대해 알아야 할 함수 및 변수의 선언이 포함되어 있습니다. –
@AdamLiss 그가 선언하는 추가 변수는 무엇입니까? – Lalaland