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

task.go 1.1 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package task
  2. import "sync"
  3. type CompleteFn = func(err error, completing func())
  4. type TaskBody[TCtx any] interface {
  5. Execute(ctx TCtx, complete CompleteFn)
  6. }
  7. type ComparableTaskBody[TCtx any] interface {
  8. TaskBody[TCtx]
  9. Compare(other TaskBody[TCtx]) bool
  10. }
  11. type Task[TCtx any] struct {
  12. body TaskBody[TCtx]
  13. isCompleted bool
  14. waiters []chan any
  15. onCompleted []func(task *Task[TCtx])
  16. waiterLock sync.Mutex
  17. err error
  18. }
  19. func (t *Task[TCtx]) Body() TaskBody[TCtx] {
  20. return t.body
  21. }
  22. func (t *Task[TCtx]) IsCompleted() bool {
  23. return t.isCompleted
  24. }
  25. func (t *Task[TCtx]) Error() error {
  26. return t.err
  27. }
  28. func (t *Task[TCtx]) Wait() {
  29. t.waiterLock.Lock()
  30. if t.isCompleted {
  31. t.waiterLock.Unlock()
  32. return
  33. }
  34. waiter := make(chan any)
  35. t.waiters = append(t.waiters, waiter)
  36. t.waiterLock.Unlock()
  37. <-waiter
  38. }
  39. func (t *Task[TCtx]) OnCompleted(callback func(task *Task[TCtx])) {
  40. t.waiterLock.Lock()
  41. if t.isCompleted {
  42. t.waiterLock.Unlock()
  43. callback(t)
  44. return
  45. }
  46. t.onCompleted = append(t.onCompleted, callback)
  47. t.waiterLock.Unlock()
  48. }

公共库

Contributors (1)