Adding array elements through multithreading

Before I go any further, this is separate from my homework. However, in the part with which I have problems, it is not the main task of the assignment.

For assignment, we simply store the numbers in the array and add the elements of the array through multithreading.

The user enters the number of threads that they would like to start, and what should be the upper limit.

For example: Upper bound: 12 Topics: 2 The application should contain elements 1-6, and then 7-12. In this case, the lower bound starts from 1, and the upper bound starts from 6. Then the second time the loop should iterate, the upper bound should be 7, and the upper bound should be 12.

I am having trouble trying to divide the upper bound by the number of threads to create increments in which the lower and upper bounds are based on.

It is quite simple if the number of threads is evenly divided by the initial upper bound. But when it is not, when I had a problem.

+4
source share
2 answers

It may be a little outside the box of what your task wants to do with the borders (not sure what you mean here). But this is a very simple example of how you could solve this problem with a fixed thread pool. Saves you the ability to independently manage flows. You # threads will be fixedThreadPool size. Then you can simply create “jobs” that add two numbers. Here you simply add the last number if you have an odd upper bound.

  private 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; } 

Perhaps this is less efficient if you had two threads reading pieces of an array, since you would say that stream 1 will add 1-6 and stream 2 to add 7-12. But this essentially does the same thing, and this approach is well suited for a more intensive computing task.

+1
source

Knitted: 18, Thread: 7

Use division to determine the nominal number of elements per thread: Ops per thread = 18/7

Use the modulo operator to determine the number of threads that should receive one additional element (for the rest): Threads with one additional = 18% 7

+3
source

Source: https://habr.com/ru/post/1398159/


All Articles