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).
Asked
Active
Viewed 646 times
-1
-
What have you tried, so far? – mrjink Jul 17 '17 at 13:27
-
is computing GCD(x,y) for each argument pair independent of computing for other arguments? That is, is GCD(x,y) pure function without side effects? – Alexei Kaigorodov Jul 17 '17 at 18:21
-
yes @AlexeiKaigorodov Kaigorodov its independent – legend Jul 18 '17 at 12:18
-
Do you know how to start a thread? Do you know how to wait for a thread to finish? If not, do some reading. If so, what's your problem? – slim Jul 18 '17 at 15:56
-
@slim , my problem is not "how to use ",its "where" and "when" to use. – legend Jul 19 '17 at 07:40
1 Answers
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
- 13,189
- 1
- 21
- 38