Advertisement
Guest User

Untitled

a guest
Dec 5th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "time"
  6. )
  7.  
  8. func main () {
  9. goRoutineTest()
  10. }
  11.  
  12. func goRoutineTest() {
  13.  
  14. workers := []Worker {{},{},{},{},{},{},{},{},{},{}}
  15.  
  16. for i := 0; i < 10; i ++ {
  17. go count(i, &workers[i]) // fires off 10 go-routines - count(i int, outside *Worker)
  18. }
  19.  
  20. time.Sleep(time.Millisecond * 100000) // wait 100 seconds
  21.  
  22. fmt.Println("\n\n") // Print final result
  23. i := 0
  24. for i < 10 {
  25. fmt.Println(" Worker ", i, " : ", workers[i].counter, " counts -",
  26. " Time spent: ", workers[i].timeSpent, "\n")
  27. i++
  28. }
  29. }
  30.  
  31. type Worker struct { // Struct declaration
  32. counter int
  33. timeSpent time.Duration
  34. }
  35.  
  36. func NewWorker() Worker { // constructor function
  37. worker := Worker{}
  38. worker.counter = 0
  39. worker.timeSpent = 0
  40. return worker
  41. }
  42.  
  43. func count ( id int, outsider *Worker) {
  44.  
  45. var tempTime time.Duration
  46. for outsider.counter < 1000 {
  47. fmt.Println("worker ", id, " : ", outsider.counter)
  48.  
  49. tempTime = time.Millisecond * time.Duration(rand.Intn(10000)) // Random wait for each thread
  50. time.Sleep(tempTime)
  51.  
  52. outsider.timeSpent += tempTime // Sum total time spent
  53. outsider.counter ++
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement