小编pea*_*xol的帖子

如何使用互斥体记录结构

我在 Go 中有一个带有互斥体的结构:

package main

import (
    "fmt"
    "sync"
)

type foo struct {
    sync.Mutex
    lastID       uint64
    nameToID map[string]uint64
}

func main() {
    fmt.Println("Hello, playground")
    foo2 := foo{lastID: 0,nameToID: map[string]uint64{"name":0}}
    fmt.Println(foo2) 
}


Run Code Online (Sandbox Code Playgroud)

上面给出了 go vet 警告(https://play.golang.org/p/J0NFgBvSGJC):

./prog.go:17:14: call of fmt.Println copies lock value: play.foo
Run Code Online (Sandbox Code Playgroud)

我看到了一个相关的 github 问题https://github.com/golang/go/issues/13675​​并了解这个警告通常需要警告复制锁。我可以通过创建一个省略锁的自定义字符串方法来解决上面的问题。然而,由于带有互斥锁的结构似乎很普遍,我想知道是否有更好/惯用的方法来记录 Go 中包含互斥锁的结构?

mutex go

5
推荐指数
1
解决办法
1198
查看次数

在ansible中,何时使用shell vs script模块来运行shell脚本

我有一个 shell 脚本 - 我可以使用本地主机上的 shell 模块和脚本模块来执行它。一种相对于另一种有什么优势?

https://docs.ansible.com/ansible/latest/modules/script_module.html#examples看来,脚本模块也将脚本复制到远程主机,然后在那里执行。因此,我的假设是否正确,对于本地主机或如果脚本已经远程存在,则两者之间没有区别。

ansible

4
推荐指数
1
解决办法
3081
查看次数

为什么Go在此代码中的Printf上检测到竞争状况

我编写了一些简单的Go代码来了解竞争条件,如下所示:

package main

import (
    "fmt"
    "sync"
)

type outer struct {
    sync.Mutex
    num int
    foo string
}

func (outer *outer) modify(wg *sync.WaitGroup) {
    outer.Lock()
    defer outer.Unlock()
    outer.num = outer.num + 1
    wg.Done()
}

func main() {
    outer := outer{
        num: 2,
        foo: "hi",
    }
    var w sync.WaitGroup
    for j := 0; j < 5000; j++ {
        w.Add(1)
        go outer.modify(&w)
    }
    w.Wait()
    fmt.Printf("Final is %+v", outer)

}

Run Code Online (Sandbox Code Playgroud)

当我在上面运行时,打印的答案始终是正确的,即num始终为5002。没有锁,由于在forloop中创建的goroutine之间存在竞争,因此答案是无法预期的。

但是,当我使用-race运行它时,将检测到以下竞争条件:


go run -race random.go
==================
WARNING: DATA RACE
Read at 0x00c00000c060 …
Run Code Online (Sandbox Code Playgroud)

go race-condition

3
推荐指数
1
解决办法
85
查看次数

标签 统计

go ×2

ansible ×1

mutex ×1

race-condition ×1