1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
| package main
import ( "fmt" "sync" "time" )
type Task struct { ID int Name string }
type TaskPool struct { mu sync.Mutex tasks []Task defaultExecutor *Executor }
type Executor struct { running bool }
func NewTaskPool() *TaskPool { return &TaskPool{} }
func (tp *TaskPool) AddTask(task Task) { tp.mu.Lock() defer tp.mu.Unlock()
tp.tasks = append(tp.tasks, task)
if tp.defaultExecutor == nil { tp.defaultExecutor = NewExecutor() } if !tp.defaultExecutor.running { tp.defaultExecutor.Start(tp) } }
func (tp *TaskPool) GetTaskCount() int { tp.mu.Lock() defer tp.mu.Unlock() return len(tp.tasks) }
func (tp *TaskPool) GetTasks(count int) []Task { tp.mu.Lock() defer tp.mu.Unlock()
if count > len(tp.tasks) { count = len(tp.tasks) }
tasks := tp.tasks[:count] tp.tasks = tp.tasks[count:]
return tasks }
func NewExecutor() *Executor { return &Executor{ running: false, } }
func (e *Executor) Start(taskPool *TaskPool) { if e.running { return }
e.running = true
go func() { for { if len(taskPool.tasks) == 0 { e.running = false break }
tasks := taskPool.GetTasks(3) for _, task := range tasks { e.executeTask(task) }
time.Sleep(time.Second) } }() }
func (e *Executor) executeTask(task Task) { fmt.Printf("Executing task ID: %d, Name: %s\n", task.ID, task.Name) time.Sleep(time.Second) }
func main() { taskPool := NewTaskPool()
taskPool.AddTask(Task{ID: 1, Name: "Task 1"}) taskPool.AddTask(Task{ID: 2, Name: "Task 2"}) taskPool.AddTask(Task{ID: 3, Name: "Task 3"}) taskPool.AddTask(Task{ID: 4, Name: "Task 4"}) taskPool.AddTask(Task{ID: 5, Name: "Task 5"})
taskPool.AddTask(Task{ID: 6, Name: "Task 6"}) taskPool.AddTask(Task{ID: 7, Name: "Task 7"}) taskPool.AddTask(Task{ID: 8, Name: "Task 8"})
time.Sleep(15 * time.Second)
taskPool.AddTask(Task{ID: 6, Name: "Task 6"}) taskPool.AddTask(Task{ID: 7, Name: "Task 7"}) taskPool.AddTask(Task{ID: 8, Name: "Task 8"})
time.Sleep(15 * time.Second) }
|