From f1cca45d8d2235daad5da3f25e74274887ccb290 Mon Sep 17 00:00:00 2001 From: Anker Jam Date: Mon, 5 Oct 2020 01:31:27 +0800 Subject: [PATCH] fix deadlock about changed sign --- pkg/task/task.go | 16 ++++++++++++++-- pkg/task/task_test.go | 19 ++++++++++++++++++- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/pkg/task/task.go b/pkg/task/task.go index 4835ad24..c8228fd2 100644 --- a/pkg/task/task.go +++ b/pkg/task/task.go @@ -468,21 +468,33 @@ func StopTask() { // AddTask add task with name func AddTask(taskname string, t Tasker) { + isChanged := false taskLock.Lock() - defer taskLock.Unlock() t.SetNext(nil, time.Now().Local()) AdminTaskList[taskname] = t if isstart { + isChanged = true + } + taskLock.Unlock() + + if isChanged { changed <- true } + } // DeleteTask delete task with name func DeleteTask(taskname string) { + isChanged := false + taskLock.Lock() - defer taskLock.Unlock() delete(AdminTaskList, taskname) if isstart { + isChanged = true + } + taskLock.Unlock() + + if isChanged { changed <- true } } diff --git a/pkg/task/task_test.go b/pkg/task/task_test.go index 488729dc..f58e374b 100644 --- a/pkg/task/task_test.go +++ b/pkg/task/task_test.go @@ -36,7 +36,24 @@ func TestParse(t *testing.T) { } AddTask("taska", tk) StartTask() - time.Sleep(6 * time.Second) + time.Sleep(3 * time.Second) + StopTask() +} + +func TestModifyTaskListAfterRunning(t *testing.T) { + tk := NewTask("taska", "0/30 * * * * *", func(ctx context.Context) error { + fmt.Println("hello world") + return nil + }) + err := tk.Run(nil) + if err != nil { + t.Fatal(err) + } + AddTask("taska", tk) + StartTask() + DeleteTask("taska") + AddTask("taska1", tk) + time.Sleep(3 * time.Second) StopTask() }