避免使用Golang中的数据竞争问题

huangapple go评论134阅读模式
英文:

Avoid data race worker with golang

问题

我有一个jobWorker,它应该处理作业,在这个worker中有数据库读写、日志文件、接收API和一些数据计算。

var mystruct struct{}

func worker(v) {
   从数据库获取数据
   ...
   更新数据库状态
   ...
   useByWorker()
   ...
   进行一些计算
   ...
   接收API
   ...
   写入日志文件
}

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

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()
}

数据竞争问题导致日志和我在worker中使用的数据混乱。有没有简单的方法可以解决数据竞争问题而不使用锁(Mutex.Lock)?我希望作业可以更快地由worker处理。有什么建议或提示吗?谢谢。

英文:

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.

答案1

得分: 1

如果你想要非阻塞的写入文件访问,你可以使用一个 goroutine 来写入文件,并通过通道传递消息。通过使用通道缓冲可以避免阻塞。

或者你可以使用标准日志记录器。它可以与多个 goroutine 一起工作。

英文:

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.

huangapple
  • 本文由 发表于 2017年8月17日 14:43:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/45728236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定