Professional Documents
Culture Documents
Go - Concurrency
Go - Concurrency
Go - Concurrency
Paradigms
CSI2120
Jochen Lang
EECS, University of Ottawa
Canada
System Programming: Go
• Physical
– Multiple processes/threads share different processors or
cores
• Logical
– Multiple processes/threads share execution time on a single
processor.
• Distributed
– Processes/threads of an application share several machines
over a network
• CSP
– Based on the idea that avoiding data sharing will avoid the
biggest problem in concurrent programming
– Threads in CSP do not communicate by sharing data
– Rather they share data by communicating
– Timing of threads is based on messaging between threads
func main() {
runtime.GOMAXPROCS(3)
sTime := time.Now(); // time it
fmt.Println("Starting")
go letters() // goroutine A
go numbers() // goroutine B
fmt.Println("Waiting …")
time.Sleep(2*time.Second)
fmt.Println("\nDone\n")
eTime := time.Now();
fmt.Printf("Run time: %s", eTime.Sub(sTime))
}
func numbers() {
for number := 1; number < 27; number++ {
// pause before every print
time.Sleep(10*time.Millisecond)
fmt.Printf("%d ", number)
}
}
func letters() {
for char := 'a'; char < 'a'+26; char++ {
time.Sleep(10)
fmt.Printf("%c ", char)
}
}
Starting
Waiting ...
a b c d e f g h i j 1 k l m n o p q r s t 2 u v w
x y z 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26
Done
Run time: 2s
• Running it without goroutines (sequential)
Starting
a b c d e f g h i j k l m n o p q r s t u v w x y
z 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 Waiting ...
Done
Run time: 2.286s
• See sync/waitgroup.go