Weiwei
Weiwei

Reputation: 17

Avoid data race worker with golang

I have a jobWorker which should deal with jobs and in this worker had database read write, log file, receive api and some data computing.

var mystruct strcut{}

func worker(v) {
   Get data from database
   ...
   Update database status
   ...
   useByWorker()
   ...
   Do some computing
   ...
   Receive API
   ...
   Write log file
}

func useByWorker() {
    mystruct = {1,2,3}
}

Here is my main func to run go-worker.

func main() {
    var wg sync.WaitGroup
    data := [][]string{}
    wg.Add(1)
    for k,v := range data {
        k := k
        v := v
        go func(k int, v []string) {
            fmt.Println(k,v)
            worker(v)
            wg.Done()
        }(k, v)
    }

    wg.Wait()
}

Data race problem let the log and my data used in worker mix up. Any way can simply fix data race problem without lock(Mutex.Lock). I want jobs can be deal by worker faster.

Any suggestions or tips will helps. Thanks.

Upvotes: 0

Views: 625

Answers (1)

Sergey Krestov
Sergey Krestov

Reputation: 11

If you want non-blocking write access to file you can use one goroutine to write in file passing messages by channel. Blocks may be avoided by using Channel Buffering Or you can use standard logger. It can work with multiple goroutines.

Upvotes: 1

Related Questions