Featured image of post Cool tricks with goroutine

Cool tricks with goroutine

Cool tricks with goroutine

Using runtime.Gosched() to force schedule Goroutines

A goroutine can run and occupy a thread for a long time. This should be avoided by using runtime.Gosched() to force schedule Goroutines to switch context.

 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
38
39
package main

import (
	"fmt"
	"time"
)

func main() {
	go func() {
		for i := 1; i <= 50; i++ {
			fmt.Println("I am Goroutine 1")
		}
	}()

	go func() {
		for i := 1; i <= 50; i++ {
			fmt.Println("I am Goroutine 2")
		}
	}()

	time.Sleep(time.Second)
}

// The result will look like below, 
// one goroutine held the thread for so long.
// I am Goroutine 1
// I am Goroutine 1
// I am Goroutine 1
// I am Goroutine 1
// I am Goroutine 1
// I am Goroutine 1
// I am Goroutine 2
// I am Goroutine 2
// I am Goroutine 2
// I am Goroutine 2
// I am Goroutine 2
// I am Goroutine 2
// I am Goroutine 1
// ...
 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
package main

import (
	"fmt"
	"runtime"
	"time"
)

func main() {
	go func() {
		for i := 1; i <= 50; i++ {
			fmt.Println("I am Goroutine 1")
			runtime.Gosched()
		}
	}()

	go func() {
		for i := 1; i <= 50; i++ {
			fmt.Println("I am Goroutine 2")
			runtime.Gosched()
		}
	}()

	time.Sleep(time.Second)
}

// The result will look better like below
// I am Goroutine 1
// I am Goroutine 1
// I am Goroutine 2
// I am Goroutine 2
// I am Goroutine 1
// I am Goroutine 1
// I am Goroutine 1
// I am Goroutine 2
// I am Goroutine 2
// ...
Built with Hugo
Theme Stack designed by Jimmy