Added go scheduler example

This commit is contained in:
Jian Han 2018-04-27 23:08:11 +10:00
parent e93498f9f9
commit c842e3dc10

View File

@ -2,7 +2,8 @@ package main
import ( import (
"fmt" "fmt"
"sync" "io/ioutil"
"runtime"
"time" "time"
) )
@ -12,27 +13,43 @@ type Job struct {
text string text string
} }
func outputText(j *Job, wg *sync.WaitGroup) { func outputText(j *Job) {
defer wg.Done() fileName := j.text + ".txt"
fileContents := ""
for j.i < j.max { for j.i < j.max {
time.Sleep(1 * time.Millisecond) time.Sleep(1 * time.Millisecond)
fileContents += j.text
fmt.Println(j.text) fmt.Println(j.text)
j.i++ j.i++
} }
err := ioutil.WriteFile(fileName, []byte(fileContents), 0644)
if err != nil {
panic("Something went awry")
}
} }
func main() { func main() {
wg := new(sync.WaitGroup)
hello := new(Job) hello := new(Job)
world := new(Job)
hello.text = "hello" hello.text = "hello"
hello.i = 0 hello.i = 0
hello.max = 3 hello.max = 3
world := new(Job)
world.text = "world" world.text = "world"
world.i = 0 world.i = 0
world.max = 5 world.max = 5
go outputText(hello, wg) go outputText(hello)
go outputText(world, wg) go outputText(world)
wg.Add(2) goSched()
wg.Wait() }
func goSched() {
iterations := 10
for i := 0; i <= iterations; i++ {
go showNumber(i)
}
runtime.Gosched()
fmt.Println("Goodbye!")
}
func showNumber(num int) {
fmt.Println(num)
} }