Guest User

Untitled

a guest
Sep 24th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "bufio"
  5. "fmt"
  6. "os"
  7. "time"
  8. )
  9.  
  10. const numWorkers = 3
  11.  
  12. var (
  13. workers chan bool
  14. requests chan string
  15. )
  16.  
  17. // worker executes requests.
  18. func worker(id int) {
  19. for {
  20. switch r := <-requests; r {
  21. case "sleep":
  22. fmt.Println(id, "sleeping")
  23. time.Sleep(5 * time.Second)
  24. case "echo":
  25. fmt.Println(id, "echo")
  26. case "quit":
  27. os.Exit(0)
  28. default:
  29. panic(fmt.Sprintf("%v unkown command %q", id, r))
  30. }
  31. }
  32. }
  33.  
  34. // run runs a function and catches any panic.
  35. func run(f func(int), id int) {
  36. defer func() {
  37. if rec := recover(); rec != nil {
  38. fmt.Println("restarting failed worker: ", rec)
  39. }
  40. workers <- true
  41. }()
  42. f(id)
  43. }
  44.  
  45. // monitor ensures that as numWorkers goroutines are running
  46. // at any time.
  47. func monitor() {
  48. workers = make(chan bool, numWorkers)
  49. for i := 0; i < cap(workers); i++ {
  50. workers <- true
  51. }
  52.  
  53. id := 0
  54. for _ = range workers {
  55. id++
  56. go run(worker, id)
  57. }
  58. }
  59.  
  60. // reader reads lines from stdin and puts them in the requests channel.
  61. func reader() {
  62. requests = make(chan string)
  63.  
  64. s := bufio.NewScanner(os.Stdin)
  65. for s.Scan() {
  66. requests <- s.Text()
  67. }
  68. }
  69.  
  70. func main() {
  71. go monitor()
  72. reader()
  73. }
Add Comment
Please, Sign In to add comment