From 5ba52de63ccfc4f483c3f5cbfcf6c67bf7d54479 Mon Sep 17 00:00:00 2001 From: galih rivanto Date: Tue, 28 May 2019 15:41:15 +0700 Subject: [PATCH] fix incorrect synchronization and add race unit test --- worker/agent.go | 2 +- worker/worker_racy_test.go | 59 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 worker/worker_racy_test.go diff --git a/worker/agent.go b/worker/agent.go index 9fc5716..147e887 100644 --- a/worker/agent.go +++ b/worker/agent.go @@ -111,7 +111,7 @@ func (a *agent) work() { } func (a *agent) disconnect_error(err error) { - a.Unlock() + a.Lock() defer a.Unlock() if a.conn != nil { diff --git a/worker/worker_racy_test.go b/worker/worker_racy_test.go new file mode 100644 index 0000000..c60e387 --- /dev/null +++ b/worker/worker_racy_test.go @@ -0,0 +1,59 @@ +package worker + +import ( + "fmt" + "sync" + "testing" +) + +func TestWorkerRace(t *testing.T) { + // from example worker + // An example of worker + w := New(Unlimited) + defer w.Close() + // Add a gearman job server + if err := w.AddServer(Network, "127.0.0.1:4730"); err != nil { + t.Fatal(err) + } + // A function for handling jobs + foobar := func(job Job) ([]byte, error) { + // Do nothing here + return nil, nil + } + // Add the function to worker + if err := w.AddFunc("foobar", foobar, 0); err != nil { + fmt.Println(err) + return + } + var wg sync.WaitGroup + // A custome handler, for handling other results, eg. ECHO, dtError. + w.JobHandler = func(job Job) error { + if job.Err() == nil { + fmt.Println(string(job.Data())) + } else { + fmt.Println(job.Err()) + } + wg.Done() + return nil + } + // An error handler for handling worker's internal errors. + w.ErrorHandler = func(e error) { + fmt.Println(e) + // Ignore the error or shutdown the worker + } + // Tell Gearman job server: I'm ready! + if err := w.Ready(); err != nil { + fmt.Println(err) + return + } + // Running main loop + go w.Work() + wg.Add(1) + // calling Echo + w.Echo([]byte("Hello")) + // Waiting results + wg.Wait() + + // tear down + w.Close() +}