-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsum2.go
37 lines (32 loc) · 793 Bytes
/
sum2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
Goroutines are multiplexed as needed onto system threads. When a goroutine
executes a blocking system call, no other goroutine is blocked. We will do
the same for CPU-bound goroutines at some point, but for now, if you want
user-level parallelism you must set $GOMAXPROCS. or call
runtime.GOMAXPROCS(n).
*/
// time ./sum2 -- roughly half of ./sum on a SMP (dual-core)
package main
import "runtime"
var parts = 2
func psum(n int) (r int64) {
c := make(chan int64)
g := func(start int, end int) {
var r int64
for i := start; i < end; i++ {
r += int64(i)
}
c <- r
}
for i := 0; i < parts; i++ {
go g(i*n/parts, (i+1)*n/parts)
}
for i := 0; i < parts; i++ {
r += <-c
}
return r
}
func main() {
runtime.GOMAXPROCS(parts)
println(psum(1000000000))
}