I’m currently taking a class where we are learning about synchronization of threads. The assignment asks us to first implement a simple threading library based on pthreads. They provided us with the following header file and told us that we should not be necessary to modify it in any way:
#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.
*/
};
My question is specifically about the GracefullyExitMainThread() function. I’ve been told I need to use pthread_join() in its implementation, but I don’t know how I can pass a thread id to it when its a class method. Also, I would have thought they would include some kind of array or other structure in the header to keep track of all the threads created.
Sorry if my post is difficult to understand or read. I’m still learning all the nuances of C++ and this is my first post on stackoverflow. Any help is greatly appreciated.
One solution would be to have a static std::vector(AKA a resizable array) that stores pthread_ids in the class. Then, whenever a thread is launched, it adds its own pthread_id to the std::vector.
You could also remove the pthread_id once the thread dies, but I am fairly sure pthread_join handles dead threads correctly, so there is no need.
Thus you now have a list of all the threads that have been started in a static member available for your static function. Simply loop over the list, and join all of them.