awesome-patterns/concurrency/concurrency_in_go/main.go

64 lines
1.0 KiB
Go
Raw Normal View History

2018-04-27 15:29:19 +03:00
package main
import (
"fmt"
2018-04-27 16:08:11 +03:00
"io/ioutil"
"runtime"
2018-04-28 07:08:44 +03:00
"strconv"
2018-04-27 15:29:19 +03:00
"time"
)
type Job struct {
i int
max int
text string
}
2018-04-27 16:08:11 +03:00
func outputText(j *Job) {
fileName := j.text + ".txt"
fileContents := ""
2018-04-27 15:29:19 +03:00
for j.i < j.max {
time.Sleep(1 * time.Millisecond)
2018-04-27 16:08:11 +03:00
fileContents += j.text
2018-04-27 15:29:19 +03:00
fmt.Println(j.text)
j.i++
}
2018-04-27 16:08:11 +03:00
err := ioutil.WriteFile(fileName, []byte(fileContents), 0644)
if err != nil {
panic("Something went awry")
}
2018-04-27 15:29:19 +03:00
}
func main() {
hello := new(Job)
hello.text = "hello"
hello.i = 0
hello.max = 3
2018-04-27 16:08:11 +03:00
world := new(Job)
2018-04-27 15:29:19 +03:00
world.text = "world"
world.i = 0
world.max = 5
2018-04-27 16:08:11 +03:00
go outputText(hello)
go outputText(world)
goSched()
2018-04-28 07:08:44 +03:00
runtime.GOMAXPROCS(2)
fmt.Printf("%d thread(s) available to Go.", listThreads())
2018-04-27 16:08:11 +03:00
}
func goSched() {
iterations := 10
for i := 0; i <= iterations; i++ {
2018-04-28 07:08:44 +03:00
showNumber(i)
2018-04-27 16:08:11 +03:00
}
fmt.Println("Goodbye!")
}
func showNumber(num int) {
2018-04-28 07:08:44 +03:00
tstamp := strconv.FormatInt(time.Now().UnixNano(), 10)
fmt.Println(num, tstamp)
}
func listThreads() int {
threads := runtime.GOMAXPROCS(0)
return threads
2018-04-27 15:29:19 +03:00
}