Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "math/rand"
- "time"
- )
- func main () {
- goRoutineTest()
- }
- func goRoutineTest() {
- workers := []Worker {{},{},{},{},{},{},{},{},{},{}}
- for i := 0; i < 10; i ++ {
- go count(i, &workers[i]) // fires off 10 go-routines - count(i int, outside *Worker)
- }
- time.Sleep(time.Millisecond * 100000) // wait 100 seconds
- fmt.Println("\n\n") // Print final result
- i := 0
- for i < 10 {
- fmt.Println(" Worker ", i, " : ", workers[i].counter, " counts -",
- " Time spent: ", workers[i].timeSpent, "\n")
- i++
- }
- }
- type Worker struct { // Struct declaration
- counter int
- timeSpent time.Duration
- }
- func NewWorker() Worker { // constructor function
- worker := Worker{}
- worker.counter = 0
- worker.timeSpent = 0
- return worker
- }
- func count ( id int, outsider *Worker) {
- var tempTime time.Duration
- for outsider.counter < 1000 {
- fmt.Println("worker ", id, " : ", outsider.counter)
- tempTime = time.Millisecond * time.Duration(rand.Intn(10000)) // Random wait for each thread
- time.Sleep(tempTime)
- outsider.timeSpent += tempTime // Sum total time spent
- outsider.counter ++
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement