Quidest?

Goroutines

· Lorenzo Drumond

A goroutine is a lightweight thread managed by the Go runtime.

1go f(x, y, z)

starts a new goroutine running

1f(x, y, z)

The evaluation of f, x, y, z happens in the current goroutine and the execution of f happens in the new goroutine.

Goroutines run in the same address space, so access to shared memory must by synchronized. The sync package provides useful primitives, although you won’t need them much in Go as there are other primitives.

 1package main
 2
 3import (
 4  "fmt"
 5  "time"
 6)
 7
 8func say(s string) {
 9  for i := 0; i < 5; i++ {
10    time.Sleep(100 * time.Millisecond)
11    fmt.Println(s)
12  }
13}
14
15func main() {
16  go say("world")
17  say("hello")
18}
19
20// Output:
21// world
22// hello
23// hello
24// world
25// world
26// hello
27// hello
28// world
29// world
30// hello

References

Next -> channels-in-goroutines

#thread #computer_science #process #scheduler #golang #concurrency #cpu #pcb #programming