Created
June 4, 2023 18:45
-
-
Save kriznaraj/466291a46621507a09e9c3988a59147c to your computer and use it in GitHub Desktop.
An optimum thread alloacation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "math" | |
| "strconv" | |
| "sync" | |
| "sync/atomic" | |
| "time" | |
| ) | |
| var MAX_INT = 100000000 | |
| var CONCURRENCY = 10 | |
| var totalPrimeNumbers int32 = 0 | |
| var currentNum int32 = 2 | |
| func checkPrime(x int) int { | |
| if x&1 == 0 { | |
| return 0 | |
| } | |
| for i := 3; i <= int(math.Sqrt(float64(x))); i++ { | |
| if x%i == 0 { | |
| return 0 | |
| } | |
| } | |
| return 1 | |
| } | |
| func checkPrimeRange(x int, till int) { | |
| // fmt.Printf("checkPrimeRange [%v, %v]\n", x, till) | |
| p := 0 | |
| for x < till { | |
| p = p + checkPrime(x) | |
| x++ | |
| } | |
| atomic.AddInt32(&totalPrimeNumbers, int32(p)) | |
| } | |
| func doWork(name string, wg *sync.WaitGroup) { | |
| start := time.Now() | |
| defer wg.Done() | |
| var bucketSize int32 = 10000 | |
| for { | |
| x := atomic.AddInt32(¤tNum, bucketSize) | |
| if x-bucketSize > int32(MAX_INT) { | |
| break | |
| } | |
| checkPrimeRange(int(x-bucketSize), int(currentNum)) | |
| } | |
| fmt.Printf("thread %s completed in %s\n", name, time.Since(start)) | |
| } | |
| func main() { | |
| start := time.Now() | |
| var wg sync.WaitGroup | |
| for i := 0; i < CONCURRENCY; i++ { | |
| wg.Add(1) | |
| go doWork(strconv.Itoa(i), &wg) | |
| } | |
| wg.Wait() | |
| fmt.Println("checking till", MAX_INT, "found", totalPrimeNumbers+1, | |
| "prime numbers. took", time.Since(start)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment