|
|
|
|
Often a problem can be partitioned into smaller, independent, pieces, and worked on simultaneously using a set of related threads. Some examples of this kind of thread might be:
Here's an example of partitioning a problem -- the problem of determining the factors of a specified number. We'll start up a separate thread to test for factors within a particular range of numbers, and use as many threads as we need to obtain all the factors.
When supplied with an input parameter of 456, a typical run of this program will output something like: Finding the factors of 456 Starting thread 'Factor (2 - 99)' Factor 2 found by thread 'Factor (2 - 99)' Starting thread 'Factor (100 - 199)' Starting thread 'Factor (200 - 299)' Factor 3 found by thread 'Factor (2 - 99)' Starting thread 'Factor (300 - 399)' Starting thread 'Factor (400 - 499)' Factor 4 found by thread 'Factor (2 - 99)' Factor 6 found by thread 'Factor (2 - 99)' Factor 8 found by thread 'Factor (2 - 99)' Factor 12 found by thread 'Factor (2 - 99)' Factor 114 found by thread 'Factor (100 - 199)' Factor 19 found by thread 'Factor (2 - 99)' Factor 228 found by thread 'Factor (200 - 299)' Thread 'Factor (400 - 499)' ending (found 0 factors) Thread 'Factor (300 - 399)' ending (found 0 factors) Factor 24 found by thread 'Factor (2 - 99)' Factor 152 found by thread 'Factor (100 - 199)' Thread 'Factor (200 - 299)' ending (found 1 factors) Factor 38 found by thread 'Factor (2 - 99)' Thread 'Factor (100 - 199)' ending (found 2 factors) Factor 57 found by thread 'Factor (2 - 99)' Factor 76 found by thread 'Factor (2 - 99)' Thread 'Factor (2 - 99)' ending (found 11 factors) In the above example, while the threads do share data (the number under test), they only need to read that number. They do not need to change it. Consequently, there is no synchronization problem. |
| The page was last updated February 19, 2008 |