Code: Select all
int mid = (from+to)/2;
ComplicatedTask newtask1 = new ComplicatedTask(ia, from, mid);
ComplicatedTask newtask2 = new ComplicatedTask(ia, mid+1, to);
newtask1.fork();
int x = newtask2.compute(); //LINE A
int y = newtask1.join(); //LINE B
return x+y;
Let's make sure we are all in agreement.The order of join() and compute() is critical. Remember that fork() causes the sub-task to be submitted to the pool and another thread can execute that task in parallel to the current thread. Therefore, if you call join() on the newly created sub task, you are basically waiting until that task finishes. This means you are using up both the threads (current thread and another thread from the pool that executes the subtask) for that sub task. Instead of waiting, you should use the current thread to compute another subtask and when done, wait for another thread to finish. This means, both the threads will execute their respective tasks in parallel instead of in sequence.
Based on what's in the quote,
the newly created subtask is "tied" another thread (say T1) from the pool.
The current thread (say T2) is "tied" to newtask2.compute() if I understand you correctly.
That's exactly what you meant in the quote, isn't it?
Once we agree on that, we need to wait for the subtask to finish after calling join() on that another thread from the pool.
Is that correct?
While waiting for the subtask to finish, why can't T2 just do newtask2.compute() and return the result to the int variable x and leave if it indeed finishes the work earlier than T1 can?
I got a sense (from your explanation in different colours in the above quote) that T2 must also "accompany" T1 while waiting for the subtask to finish. Why can't T2 leave early if it finishes what it needs to do?
This quote seem to be suggesting that T2 must "accompany" T1 and wait. It also seems to suggest that leaving if T2 finishes its work early and doing something else useful would have been a better way for T2 to be spending its time instead of wasting it by "hanging out with" T1.Instead of waiting, you should use the current thread to compute another subtask and when done, wait for another thread to finish. This means, both the threads will execute their respective tasks in parallel instead of in sequence. Therefore, even though the final answer will be the same, the performance will not be the same.