Before I go any further, this IS apart of my homework.The part that I am having trouble with however, is not the main point of the assignment.
For the assignment we are just storing numbers in an array, and am adding up the elements of the array via multithreading.
The user enters how many threads that they would like to run, and what the upper bound should be.
For example: Upper Bound: 12 Threads: 2 The application should add up elements 1-6, then 7-12. In this case the lower bound starts out at 1 and the upper bound starts out at 6. Then the second time the loop should itterate the upper bound should be 7 and the upper bound should be 12.
I am having trouble trying to devide the upper bound by the number of threads to create the increments in wich the lower and upper bounds are based off of.
It is fairly simple if the number of threads devides evenly into the starting upper bound. But when It doesn't is when I am having the problem.
Thank You!
Bound: 18, Threads: 7
ReplyDeleteUse division to figure out the nominal amount of elements per thread:
Ops per thread = 18 / 7
Use the modulo operator to figure out the number of threads that should get one extra element (for the remainder):
Threads with one extra = 18 % 7
This might be a bit outside the box of what your assignment wants you to do with the bounds (not sure what you mean here). But this is a very basic example of how you could solve this with a fixed thread pool. Saves you having to manage the threads yourself. You # threads would be the size of the fixedThreadPool. Then you could just create 'jobs' which add two numbers. Here you just add the last number if you have an odd upper bound.
ReplyDeleteprivate static ExecutorService tpool = Executors.newFixedThreadPool(20);
private static final int upper = 140;
private static AtomicInteger total = new AtomicInteger(0);
public static void main(String[] args) throws Exception {
int ar[] = new int[upper];
for(int i = 1 ; i <= upper; i++){
ar[i-1]=i;
}
for(int i = 1 ; i <= ((upper%2) !=0 ? (upper-1):(upper)); i+=2){
final int a = ar[i-1];
final int b = ar[i];
Thread thread = new Thread(new Runnable(){
public void run() {
int res = add(a, b);
total.addAndGet(res);
return;
}});
tpool.execute(thread);
}
if(upper%2!=0)
total.addAndGet(ar[ar.length-1]);
tpool.shutdown(); //wait for everything to finish
System.out.println(total.get()); //get the result.
}
private static int add(final int a, final int b){
return a+b;
}
Arguably this is less efficient if you had two threads reading off chunks of the array as you would tell thread 1 to add 1-6 and thread 2 to add 7-12. But it essentially does the same thing and this approach would be well suited to a more computationally intensive task.