diff --git a/master.go b/master.go index df734bf..0c0478d 100644 --- a/master.go +++ b/master.go @@ -5,11 +5,13 @@ import ( "bytes" "errors" "io" + "sync" "time" ) type Master struct { - pool map[string]*Worker + pool map[string]*Worker + mutex sync.Mutex } func NewMaster() *Master { @@ -19,6 +21,7 @@ func NewMaster() *Master { } func (m *Master) GetWorker(id string) *Worker { + m.mutex.Lock() if m.pool == nil { m.pool = make(map[string]*Worker) } @@ -26,15 +29,19 @@ func (m *Master) GetWorker(id string) *Worker { m.pool[id] = NewWorker(id) m.pool[id].RegMaster(m) } + m.mutex.Unlock() return m.pool[id] } func (m *Master) RunWorker(id string) error { + m.mutex.Lock() if m.pool == nil { + m.mutex.Unlock() return errors.New("m.pool == nil") } worker, ok := m.pool[id] + m.mutex.Unlock() if !ok { return errors.New("can't find worker id=" + id) } @@ -75,7 +82,9 @@ func (m *Master) RunWorker(id string) error { } func (m *Master) DelWorker(id string) error { + m.mutex.Lock() if worker, ok := m.pool[id]; ok { + m.mutex.Unlock() worker.Stop() for { if !worker.Running { @@ -85,6 +94,7 @@ func (m *Master) DelWorker(id string) error { time.Sleep(20 * time.Millisecond) } } else { + m.mutex.Unlock() return errors.New("can't find worker id=" + id) } return nil