go - Golang Parallel -
i new golang , trying understand concurrency , parallel. read below mentioned article concurrency , parallel. have executed same program. not getting same ( mixed letter & character ) output. getting first letters characters. seems concurrency working not parallel not.
article says add runtime.gomaxprocs(4) make parallel.
why not getting parallel out ?
i using 4 core cpu system , go version 1.8.2
https://www.goinggo.net/2014/01/concurrency-goroutines-and-gomaxprocs.html
i know if add sleep can see parallel output, per concurrency concept . parallelism says if system has more 1 cpu, each thread run in 1 cpu , becomes parallel process. question here why not getting parallel output though system has 4 core , added runtime.gomaxprocs(4), .
go program
package main import ( "fmt" "runtime" "sync" ) func main() { runtime.gomaxprocs(2) var wg sync.waitgroup wg.add(2) fmt.println("starting go routines") go func() { defer wg.done() char := ‘a’; char < ‘a’+26; char++ { fmt.printf("%c ", char) } }() go func() { defer wg.done() number := 1; number < 27; number++ { fmt.printf("%d ", number) } }() fmt.println("waiting finish") wg.wait() fmt.println("\nterminating program") }
my output
starting go routines waiting finish 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 b c d e f g h j k l m n o p q r s t u v w x y z terminating program
expected output ( not same , parallel output )
starting go routines waiting finish b 1 2 3 4 c d e f 5 g h 6 7 j 8 k 9 10 11 12 l m n o p q 13 r s 14 t 15 u v 16 w 17 x y 18 z 19 20 21 22 23 24 25 26 terminating program
in opinion there 2 troubles can in code. first idea:
runtime.gomaxprocs(2)
using row allow 2 workers, starting 3 go routines (main takes one).
but main problem go routines finished fast. adding
time.sleep(100000)
will solve problem. package main
import ( "fmt" "runtime" "sync" ) func main() { runtime.gomaxprocs(3) var wg sync.waitgroup wg.add(2) fmt.println("starting go routines") go func() { defer wg.done() char := 'a'; char < 'a'+26; char++ { := 0; < 10000; i++ { _ = * 2 } fmt.printf("%c ", char) } }() go func() { defer wg.done() number := 1; number < 27; number++ { := 0; < 10000; i++ { _ = * 2 } fmt.printf("%d ", number) } }() fmt.println("waiting finish") wg.wait() fmt.println("\nterminating program") }
in case i've tried not use sleep function, because change thread status in scheduler. , have result.
starting go routines waiting finish 1 2 3 4 5 b 6 c d 7 8 e f 9 g h 10 j 11 k 12 l m 13 n 14 o p q 15 r 16 s 17 t u 18 v 19 w 20 x y 21 z 22 23 24 25 26 terminating program
Comments
Post a Comment