I was waiting for the move to be made, so that I could post my thesis on the subject.
>Beginners answer: Logically, yeah.
As a beginner I am not yet convinced. Despite the fact that I really want to.
Assume that our system allows us to run code in parallel. Focus ONLY on what the code I wrote does.
Let me explain things a bit more analytically.
I am writting the code in C++ and I have to use pthread. I have to write in C++ too.
There are two classes, Job and JobListener.
computePi inherits from Job and its actual word to do is the "Run()" method.
PiJobListener inherits from JobListener and actually, prints the result the data member of computePi, named Pi, which holds the result of Run() method.
There is a class Scheduler to schedule all the jobs.
In main function, there is a loop, something like that:
Code:
JobScheduler scheduler();
for (int i = 0; i < 3; ++i) {
ComputePi* pi = new ComputePi(100000 * i * i);
PiJobListener* pi_listener = new PiJobListener();
scheduler.schedule(pi, pi_listener);
}
Then inside Scheduler, I have a vector (named thread), which holds pointers to a class named Task.
Task class actually has as data members the Job, the JobListener, a pthread and an exit code. I am not sure if I should use the Task class or not.
The schedule method, does this thread.push_back(new Task(job, listener));
In the constructor of Task, I do create a thread to execute ComputePi.Run(), then I join the thread (after checking that it was created without errors) and then I call the listener of the job to print the result!
In the constructor of Task I delete the job, the listener and the task.
I have the feeling that this way, I do make the code run in serial, because of using pthread_join().
Here is the code
Code:
Task(Job* job_, JobListener* listener_)
: job(job_), listener(listener_), exit_code((void*)-1) {
int not_ok = pthread_create( &thread, NULL, &Job::RunHelper, job);
if(not_ok) std::cout << "Error at creation\n";
pthread_join(thread, &exit_code);
listener->handle((int)exit_code, *job); //print data member of job, i.e. the result
}
If I remove join(), then the handle(), seems to print the data member of job pi, before Run() is done.
The serial execution of code, as I **believe** it is done.
I tried to put the join and the listener->handle (which actually is the method that prints the result) in the destructor of Task, by I didn't get any results!
So, my questions are:
1)Am I right that I make the code run in serial? If so, is it because join I guess, right?
2)What happens to a thread created like this: pthread_create( &thread, NULL, &Job::RunHelper, job);
i.e. with NULL as attribute when it terminates, assuming we haven't called join at any point of it? When it is done, it will "free it self, like detached threads do"?
3)If I am right and the code is being executed in serial, how should I make it run in parallel?