Goroutine unit manager
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

manager_test.go 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package gum
  2. import (
  3. "log"
  4. "os"
  5. "syscall"
  6. "testing"
  7. "time"
  8. )
  9. var WorkerID int
  10. type Worker struct{}
  11. // Example loop, it will be spwaned in a goroutine
  12. func (w *Worker) Run(um UnitManager) {
  13. ticker := time.NewTicker(time.Second)
  14. // Worker's loop
  15. for {
  16. select {
  17. case <-ticker.C:
  18. log.Println("tick")
  19. // Read from channel if this worker unit should stop
  20. case <-um.ShouldStop():
  21. // Shutdown work for current unit
  22. w.Shutdown()
  23. // Notify manager that this unit is done.
  24. um.Done()
  25. }
  26. }
  27. }
  28. func (w *Worker) Shutdown() {
  29. // Do shutdown procedure for worker
  30. return
  31. }
  32. func NewWorker() *Worker {
  33. return &Worker{}
  34. }
  35. func DoRunMain(pid chan int, quit chan<- bool) {
  36. pid <- os.Getpid()
  37. // Create a unit manager
  38. manager := NewManager()
  39. // Shutdown all units on SIGINT
  40. manager.ShutdownOn(os.Interrupt)
  41. // NewWorker returns a type implementing WorkUnit interface unit :=
  42. worker1 := NewWorker()
  43. worker2 := NewWorker()
  44. // Register the unit with the manager
  45. manager.AddUnit(worker1)
  46. manager.AddUnit(worker2)
  47. // Start the manager
  48. go manager.Run()
  49. // Wait for all units to shutdown gracefully through their `Shutdown` method
  50. quit <- <-manager.Quit
  51. }
  52. func TestRunMain(t *testing.T) {
  53. mainPid := make(chan int, 1)
  54. quit := make(chan bool)
  55. go DoRunMain(mainPid, quit)
  56. time.Sleep(3 * time.Second)
  57. syscall.Kill(<-mainPid, syscall.SIGINT)
  58. <-quit
  59. }