Reputation: 9809
I have a function which splits an array into smaller pieces.
Each piece is then evaluated in a separate thread.
The results are populated into a common list.
private void sortandkeep(int[] arr){
traversed.add(arr);
if(arr.length==1) return;
List<Integer> layer=new ArrayList<Integer>();
//Divide the layer into different parts for a barrier to be set up.
//After the barrier is broken,the layer is added to the main list
if(arr.length>4){
List<int[]> parts=split(arr);//smaller split pieces are populated on the list
CyclicBarrier barrier = new CyclicBarrier(parts.size());
for(int[] e:parts){
Thread t=new Thread(new sortingThread(barrier,e,layer));
t.start();
}
}
else
.........
//The main thread should not proceed,unless the above barrier is broken
sortandkeep(toIntArray(layer));
}
I would have expected the sortandkeep recursion to wait for the barrier to be broken.
This would happen when all the worker threads have invoked await.
However,this is not so.
The main thread keeps recursing - irrespective of the state of the worker threads.
How is this so?
Upvotes: 2
Views: 298
Reputation: 14730
If the main thread must wait for all the other threads to complete their tasks, then that thread is one of the parties which have to go through the barrier, and it must invoke await
as well, before proceeding.
// [...]
CyclicBarrier barrier = new CyclicBarrier(parts.size() + 1); // sorting threads AND main thread
for(int[] e:parts){
Thread t=new Thread(new sortingThread(barrier,e,layer));
t.start();
}
} else
// [...]
//The main thread should not proceed, unless the above barrier is broken
barrier.await();
sortandkeep(toIntArray(layer));
// [...]
Upvotes: 1