mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2025-02-16 13:43:13 +03:00
Added go scheduler example
This commit is contained in:
parent
e93498f9f9
commit
c842e3dc10
@ -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)
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user