worker/types/worker: make ID allocation atomic

Message IDs are allocated for both messages from UI to workers and the other
way around. Hence, the global nextId variable is accessed from multiple
goroutines.

Instead, use atomic to access the global counter.
This commit is contained in:
Simon Ser 2019-05-19 09:50:19 +00:00 committed by Drew DeVault
parent 34dd6bc635
commit f27db33305
2 changed files with 11 additions and 10 deletions

View File

@ -12,13 +12,13 @@ import (
type WorkerMessage interface { type WorkerMessage interface {
InResponseTo() WorkerMessage InResponseTo() WorkerMessage
getId() int getId() int64
setId(id int) setId(id int64)
} }
type Message struct { type Message struct {
inResponseTo WorkerMessage inResponseTo WorkerMessage
id int id int64
} }
func RespondTo(msg WorkerMessage) Message { func RespondTo(msg WorkerMessage) Message {
@ -31,11 +31,11 @@ func (m Message) InResponseTo() WorkerMessage {
return m.inResponseTo return m.inResponseTo
} }
func (m Message) getId() int { func (m Message) getId() int64 {
return m.id return m.id
} }
func (m Message) setId(id int) { func (m Message) setId(id int64) {
m.id = id m.id = id
} }

View File

@ -3,9 +3,10 @@ package types
import ( import (
"log" "log"
"sync" "sync"
"sync/atomic"
) )
var nextId int = 1 var lastId int64 = 1 // access via atomic
type Backend interface { type Backend interface {
Run() Run()
@ -17,7 +18,7 @@ type Worker struct {
Messages chan WorkerMessage Messages chan WorkerMessage
Logger *log.Logger Logger *log.Logger
callbacks map[int]func(msg WorkerMessage) // protected by mutex callbacks map[int64]func(msg WorkerMessage) // protected by mutex
mutex sync.Mutex mutex sync.Mutex
} }
@ -26,13 +27,13 @@ func NewWorker(logger *log.Logger) *Worker {
Actions: make(chan WorkerMessage, 50), Actions: make(chan WorkerMessage, 50),
Messages: make(chan WorkerMessage, 50), Messages: make(chan WorkerMessage, 50),
Logger: logger, Logger: logger,
callbacks: make(map[int]func(msg WorkerMessage)), callbacks: make(map[int64]func(msg WorkerMessage)),
} }
} }
func (worker *Worker) setId(msg WorkerMessage) { func (worker *Worker) setId(msg WorkerMessage) {
msg.setId(nextId) id := atomic.AddInt64(&lastId, 1)
nextId++ msg.setId(id)
} }
func (worker *Worker) setCallback(msg WorkerMessage, func (worker *Worker) setCallback(msg WorkerMessage,