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.

175 lines
4.6 KiB

9 years ago
9 years ago
9 years ago
  1. package common
  2. import (
  3. "sync/atomic"
  4. )
  5. //----------------------------------------
  6. // Task
  7. // val: the value returned after task execution.
  8. // err: the error returned during task completion.
  9. // abort: tells Parallel to return, whether or not all tasks have completed.
  10. type Task func(i int) (val interface{}, err error, abort bool)
  11. type TaskResult struct {
  12. Value interface{}
  13. Error error
  14. }
  15. type TaskResultCh <-chan TaskResult
  16. type taskResultOK struct {
  17. TaskResult
  18. OK bool
  19. }
  20. type TaskResultSet struct {
  21. chz []TaskResultCh
  22. results []taskResultOK
  23. }
  24. func newTaskResultSet(chz []TaskResultCh) *TaskResultSet {
  25. return &TaskResultSet{
  26. chz: chz,
  27. results: make([]taskResultOK, len(chz)),
  28. }
  29. }
  30. func (trs *TaskResultSet) Channels() []TaskResultCh {
  31. return trs.chz
  32. }
  33. func (trs *TaskResultSet) LatestResult(index int) (TaskResult, bool) {
  34. if len(trs.results) <= index {
  35. return TaskResult{}, false
  36. }
  37. resultOK := trs.results[index]
  38. return resultOK.TaskResult, resultOK.OK
  39. }
  40. // NOTE: Not concurrency safe.
  41. // Writes results to trs.results without waiting for all tasks to complete.
  42. func (trs *TaskResultSet) Reap() *TaskResultSet {
  43. for i := 0; i < len(trs.results); i++ {
  44. var trch = trs.chz[i]
  45. select {
  46. case result, ok := <-trch:
  47. if ok {
  48. // Write result.
  49. trs.results[i] = taskResultOK{
  50. TaskResult: result,
  51. OK: true,
  52. }
  53. } else {
  54. // We already wrote it.
  55. }
  56. default:
  57. // Do nothing.
  58. }
  59. }
  60. return trs
  61. }
  62. // NOTE: Not concurrency safe.
  63. // Like Reap() but waits until all tasks have returned or panic'd.
  64. func (trs *TaskResultSet) Wait() *TaskResultSet {
  65. for i := 0; i < len(trs.results); i++ {
  66. var trch = trs.chz[i]
  67. result, ok := <-trch
  68. if ok {
  69. // Write result.
  70. trs.results[i] = taskResultOK{
  71. TaskResult: result,
  72. OK: true,
  73. }
  74. } else {
  75. // We already wrote it.
  76. }
  77. }
  78. return trs
  79. }
  80. // Returns the firstmost (by task index) error as
  81. // discovered by all previous Reap() calls.
  82. func (trs *TaskResultSet) FirstValue() interface{} {
  83. for _, result := range trs.results {
  84. if result.Value != nil {
  85. return result.Value
  86. }
  87. }
  88. return nil
  89. }
  90. // Returns the firstmost (by task index) error as
  91. // discovered by all previous Reap() calls.
  92. func (trs *TaskResultSet) FirstError() error {
  93. for _, result := range trs.results {
  94. if result.Error != nil {
  95. return result.Error
  96. }
  97. }
  98. return nil
  99. }
  100. //----------------------------------------
  101. // Parallel
  102. // Run tasks in parallel, with ability to abort early.
  103. // Returns ok=false iff any of the tasks returned abort=true.
  104. // NOTE: Do not implement quit features here. Instead, provide convenient
  105. // concurrent quit-like primitives, passed implicitly via Task closures. (e.g.
  106. // it's not Parallel's concern how you quit/abort your tasks).
  107. func Parallel(tasks ...Task) (trs *TaskResultSet, ok bool) {
  108. var taskResultChz = make([]TaskResultCh, len(tasks)) // To return.
  109. var taskDoneCh = make(chan bool, len(tasks)) // A "wait group" channel, early abort if any true received.
  110. var numPanics = new(int32) // Keep track of panics to set ok=false later.
  111. ok = true // We will set it to false iff any tasks panic'd or returned abort.
  112. // Start all tasks in parallel in separate goroutines.
  113. // When the task is complete, it will appear in the
  114. // respective taskResultCh (associated by task index).
  115. for i, task := range tasks {
  116. var taskResultCh = make(chan TaskResult, 1) // Capacity for 1 result.
  117. taskResultChz[i] = taskResultCh
  118. go func(i int, task Task, taskResultCh chan TaskResult) {
  119. // Recovery
  120. defer func() {
  121. if pnk := recover(); pnk != nil {
  122. atomic.AddInt32(numPanics, 1)
  123. // Send panic to taskResultCh.
  124. taskResultCh <- TaskResult{nil, ErrorWrap(pnk, "Panic in task")}
  125. // Closing taskResultCh lets trs.Wait() work.
  126. close(taskResultCh)
  127. // Decrement waitgroup.
  128. taskDoneCh <- false
  129. }
  130. }()
  131. // Run the task.
  132. var val, err, abort = task(i)
  133. // Send val/err to taskResultCh.
  134. // NOTE: Below this line, nothing must panic/
  135. taskResultCh <- TaskResult{val, err}
  136. // Closing taskResultCh lets trs.Wait() work.
  137. close(taskResultCh)
  138. // Decrement waitgroup.
  139. taskDoneCh <- abort
  140. }(i, task, taskResultCh)
  141. }
  142. // Wait until all tasks are done, or until abort.
  143. // DONE_LOOP:
  144. for i := 0; i < len(tasks); i++ {
  145. abort := <-taskDoneCh
  146. if abort {
  147. ok = false
  148. break
  149. }
  150. }
  151. // Ok is also false if there were any panics.
  152. // We must do this check here (after DONE_LOOP).
  153. ok = ok && (atomic.LoadInt32(numPanics) == 0)
  154. return newTaskResultSet(taskResultChz).Reap(), ok
  155. }