-1

How to multithread a task among nesting for-loops (say 2). Consider the task is to find the GCD(x,y) where 'x' and 'y' are large, say 10^6. I create 10 threads and want each thread to compute GCD for unique (x,y).

mrjink
  • 1,102
  • 1
  • 20
  • 26
legend
  • 1
  • 1

1 Answers1

0

The solution consists of 3 parts. The central part is a queue of restricted size to keep small tasks each of which computes GCD(x,y) for given x and y. First part is a thread which makes nesting for-loops and for each x and y makes new task and puts it to the queue. When the queue is full, method queue.put() blocks to avoid memory saturation. The last part is a pool of threads which take tasks from the queue and execute them. You can implement working threads from scratch, or make a thread pool with blocking queue as it is described in Best practice for executing large number of tasks

Alexei Kaigorodov
  • 12,853
  • 1
  • 19
  • 36