В настоящее время я занимаюсь классом, где мы изучаем синхронизацию потоков. Назначение просит нас сначала реализовать простую библиотеку потоков на основе 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()
в своей реализации, но я не знаю, как я могу передать ему идентификатор потока, когда это метод класса. Кроме того, я бы подумал, что они будут включать в заголовок какой-то массив или другую структуру, чтобы отслеживать все созданные потоки.
Извините, если мой пост трудно понять или прочитать. Я все еще изучаю все нюансы C++, и это мой первый пост в stackoverflow. Любая помощь приветствуется.
Существует„или“в определении GracefullyExitMainThread, что делает его невозможно реализовать. Выбери один. – stark
В общем случае вы не хотите объявлять переменные в файлах заголовков; вы делаете это непосредственно в файле .c или .cpp. Заголовок содержит декларации функций и переменных, о которых должны знать _other_ исходные файлы. –
@AdamLiss Какие дополнительные переменные он объявляет? – Lalaland