互斥锁似乎没有正确锁定

时间:2018-03-18 03:48:02

标签: go

我只是在学习互动。我认为下面的程序总共会返回1000,但是我得到了不同的结果,所以我认为我做错了...

package main

import (
    "fmt"
    "sync"
)

var total int
var locker sync.RWMutex

func add() {
    for x := 1; x <= 100; x++ {
        locker.Lock()
        total += 1
        locker.Unlock()
    }
}

func main() {
    for x := 1; x <= 10; x++ {
        go add()
    }
    fmt.Printf("Total is %v\n", total)
}

3 个答案:

答案 0 :(得分:2)

在检查结果之前,你不是在等待你开始完成的任何goroutine。使用WaitGroup等待所有这些内容完成。

答案 1 :(得分:2)

主要功能在gorutines完成作品之前返回,您应该添加sync.WaitGroup,此代码按预期工作:https://play.golang.com/p/_OfrZae0soB

package main

import (
    "fmt"
    "sync"
)

var total int
var locker sync.RWMutex

func add(wg *sync.WaitGroup) {
    defer wg.Done()
    for x := 1; x <= 100; x++ {
        locker.Lock()
        total += 1
        locker.Unlock()
    }
}

func main() {
    var wg sync.WaitGroup
    for x := 1; x <= 10; x++ {
        wg.Add(1)
        go add(&wg)
    }
    wg.Wait()
    fmt.Printf("Total is %v\n", total)
}

答案 2 :(得分:1)

您有数据竞争。因此,结果未定义。

package main

import (
    "fmt"
    "sync"
)

var total int
var locker sync.RWMutex

func add() {
    for x := 1; x <= 100; x++ {
        locker.Lock()
        total += 1
        locker.Unlock()
    }
}

func main() {
    for x := 1; x <= 10; x++ {
        go add()
    }
    fmt.Printf("Total is %v\n", total)
}

输出:

$ go run -race racer.go
==================
WARNING: DATA RACE
Read at 0x0000005ba408 by main goroutine:
  runtime.convT2E64()
      /home/peter/go/src/runtime/iface.go:335 +0x0
  main.main()
      /home/peter/src/racer.go:23 +0x84

Previous write at 0x0000005ba408 by goroutine 14:
  main.add()
      /home/peter/src/racer.go:14 +0x76

Goroutine 14 (running) created at:
  main.main()
      /home/peter/src/racer.go:21 +0x52
==================
Total is 960
Found 1 data race(s)
exit status 66
$