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