I am trying concurrency in Go, but I am stuck and have no idea what to do with it.
Suppose, I have a code like this.
n := 9999999
count := 0
primePalindrome := 0
for i := 0; count < n; i {
if PrimeNumber(i) && PalindromeNumber(i) {
primePalindrome = i
count
}
}
The function of the code is to find nth prime palindrome numbers.
eg: 1st to 9th palindrome sequence is 2, 3, 5, 7, 11, 101, 131, 151
The question is, what if I want to find the 9999999th palindrome with faster runtime using Go concurrency, how to apply concurrency in PrimeNumber() and PalindromeNumber() function?
My current code is like this
for i := 0; count < n; i {
go PrimeNumber(i)
go PalindromeNumber(i)
if PrimeNumber(i) && PalindromeNumber(i) {
primePalindrome = i
count
}
}
How do I know that function PrimeNumber(i) and PalindromeNumber(i) already executed and done by go routine so that I can give IF CONDITION to get the number?
CodePudding user response:
There are multiple issues to solve here:
- we want to spin off "is prime" and "is palindrome" tests
- we want to sequentially order the numbers that pass the tests
- and of course, we have to express the "spin off" and "wait for result" parts of the problem in our programming language (in this case, Go).
(Besides this, we might want to optimize our primality testing, perhaps with a Sieve of Eratothenese algorithm or similar, which may also involve parallelism.)
The middle problem here is perhaps the hardest one. There is a fairly obvious way to do it, though: we can observe that if we assign an ascending-order number to each number tested, the answers that come back (n is/isnot suitable), even if they come back in the wrong order, are easily re-shuffled into order.
Since your overall loop increments by 1 (which is kind of a mistake1), the numbers tested are themselves suitable for this purpose. So we should create a Go channel whose type is a pair of results: Here is the number I tested, and here is my answer:
type result struct {
tested int // the number tested
passed bool // pass/fail result
}
testC := make(chan int)
resultC := make(chan result)
Next, we'll use a typical "pool of workers". Then we run our loop of things-to-test. Here is your existing loop:
for i := 0; count < n; i {
go PrimeNumber(i)
go PalindromeNumber(i)
if PrimeNumber(i) && PalindromeNumber(i) {
primePalindrome = i
count
}
}
We'll restructure this as:
count := 0
busy := 0
results := []result{}
for toTest := 0;; toTest = 2 {
// if all workers are busy, wait for one result
if busy >= numWorkers {
result := <-resultC // get one result
busy--
results := addResult(results, result)
if result.passed {
count // passed: increment count
if count >= n {
break
}
}
}
// still working, so test this number
testC <- toTest
busy
}
close(testC) // tell workers to stop working
// collect remaining results
for result := range resultC {
results := addResult(results, result)
}
(The "busy" test is a bit klunky; you could use a select to send or receive, whichever you can do first, instead, but if you do that, the optimizations outlined below get a little more complicated.)
This does mean our standard worker pool pattern needs to close the result channel resultC
, which means we'll add a sync.WaitGroup
when we spawn off the numWorkers
workers:
var wg sync.WaitGroup
wg.Add(numWorkers)
for i := 0; i < numWorkers; i {
go worker(&wg, testC, resultC)
}
go func() {
wg.Wait()
close(resultC)
}()
This makes our for result := range resultC
loop work; the workers all stop (and return and call wg.Done()
via their defer
s, which are not shown here) when we close testC
so resultC
is closed once the last worker exits.
Now we have one more problem, which is: the results come back in semi-random order. That's why we have a slice of results. The addResult
function needs to expand the slice and insert the result in the proper position, using the value-tested. When the main loop reaches the break
statement, the number in toTest
is at least the n'th palindromic prime, but it may be great than the n'th. So we need to collect the remaining results and look backwards to see if some earlier number was in fact the n'th.
There are a number of optimizations to make at this point: in particular, if we've tested numbers through k and they're all known to have passed or failed and k numWorkers < n, we no longer need any of these results (whether they passed or failed) so we can shrink the results slice. Or, if we're interested in building a table of palindromic primes, we can do that, or anything else we might choose. The above is not meant to be the best solution, just a solution.
Note again that we "overshoot": whatever numWorkers
is, we may test up to numWorkers-1
values that we didn't need to test at all. That, too, might be optimizable by having each worker quit early (using some sort of quit indicator, whether that's a "done" channel or just a sync/atomic
variable) if they're working on a number that's higher than the now-known-to-be-at-least-n'th value.
1We can cut the problem in half by starting with answers pre-loaded with 2, or 1 and 2 if you choose to consider 1 prime—see also http://ncatlab.org/nlab/show/too simple to be simple. Then we run our loop from 3 upwards by 2 each time, so that we don't even bother testing even numbers, since 2 is the only even prime number.
CodePudding user response:
The answer depends of many aspects of your problem
For instance, if each step is independent, you can use the example below. If the next step depends on the previous you need to find another solution.
For instance: a palindrome number does not depends of the previous number. You can paralelize the palindrome detection. While the prime is a sequential code.
Perhaps check if a palindrome is prime by checking the divisors until the square root of that number. You need to benchmark it
numbers := make(chan int, 1000) // add some buffer
var wg sync.WaitGroup
for … { // number of consumers
wg.Add(1)
go consume(&wg, numbers)
}
for i … {
numbers <- i
}
close(numbers)
wg.Wait()
// here all consumers ended properly
…
func consume(wg *sync.WaitGroup, numbers chan int){
defer wg.Done()
for i := range numbers {
// use i
}
}