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