tvm.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. package executor
  2. import (
  3. "errors"
  4. "sync"
  5. "github.com/google/uuid"
  6. )
  7. var ErrTicketPoolFull = errors.New("ticket pool full")
  8. var ErrTicketNotTaken = errors.New("ticket not taken")
  9. var ErrTicketNotFound = errors.New("ticket not found")
  10. type Ticket struct {
  11. Index int
  12. UUID string
  13. Taken bool
  14. }
  15. type TVM struct {
  16. mutex sync.Mutex
  17. tickets map[int]*Ticket
  18. size int
  19. }
  20. func NewTVM(size int) *TVM {
  21. tickets := map[int]*Ticket{}
  22. for i := 0; i < size; i++ {
  23. tickets[i] = &Ticket{
  24. Index: i,
  25. UUID: "",
  26. Taken: false,
  27. }
  28. }
  29. return &TVM{
  30. tickets: tickets,
  31. size: size,
  32. }
  33. }
  34. func (this *TVM) AcquireTicket() (*Ticket, error) {
  35. this.mutex.Lock()
  36. defer this.mutex.Unlock()
  37. for i := range len(this.tickets) {
  38. if this.tickets[i].Taken {
  39. continue
  40. }
  41. this.tickets[i].UUID = uuid.New().String()
  42. this.tickets[i].Taken = true
  43. return this.tickets[i], nil
  44. }
  45. return nil, ErrTicketPoolFull
  46. }
  47. func (this *TVM) ReleaseTicket(UUID string) error {
  48. this.mutex.Lock()
  49. defer this.mutex.Unlock()
  50. for index, ticket := range this.tickets {
  51. if ticket.UUID != UUID {
  52. continue
  53. }
  54. if !ticket.Taken {
  55. return ErrTicketNotTaken
  56. }
  57. this.tickets[index].UUID = ""
  58. this.tickets[index].Taken = false
  59. return nil
  60. }
  61. return ErrTicketNotFound
  62. }
  63. func (this *TVM) FindTicket(UUID string) (*Ticket, error) {
  64. this.mutex.Lock()
  65. defer this.mutex.Unlock()
  66. for _, ticket := range this.tickets {
  67. if ticket.UUID != UUID {
  68. continue
  69. }
  70. if !ticket.Taken {
  71. return nil, ErrTicketNotTaken
  72. }
  73. return ticket, nil
  74. }
  75. return nil, ErrTicketNotFound
  76. }
  77. func (this *TVM) Capacity() int {
  78. this.mutex.Lock()
  79. defer this.mutex.Unlock()
  80. counter := 0
  81. for i := range len(this.tickets) {
  82. if !this.tickets[i].Taken {
  83. counter += 1
  84. }
  85. }
  86. return counter
  87. }
  88. func (this *TVM) HasTicket(UUID string) bool {
  89. this.mutex.Lock()
  90. defer this.mutex.Unlock()
  91. for _, ticket := range this.tickets {
  92. if ticket.UUID != UUID {
  93. continue
  94. }
  95. return ticket.Taken
  96. }
  97. return false
  98. }