0

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.

Weiwei
  • 17
  • 3
  • 2
    Your use of WaitGroup in the `main` is suspicious - you only call `Add(1)` once but then call `Done` multiple times (for each element in the `data`) in the goroutine. – ain Aug 17 '17 at 06:50
  • "I want jobs can be deal by worker faster." --- do you seriously think few nanoseconds would make any of your code slower? – zerkms Aug 17 '17 at 08:36
  • Time consume at waiting API or DB response. The main problem of this question is that how should I do these jobs in the same time and independently without data race. – Weiwei Aug 17 '17 at 08:43

1 Answers1

1

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.