相关疑难解决方法(0)

没有锁定同时读取函数指针是否安全?

假设我有这个:

go func() {
    for range time.Tick(1 * time.Millisecond) {
        a, b = b, a
    }
}()
Run Code Online (Sandbox Code Playgroud)

其他地方:

i := a // <-- Is this safe?
Run Code Online (Sandbox Code Playgroud)

对于这个问题,i与原始a或者相关的价值是不重要的b.唯一的问题是阅读a是否安全.也就是说,是否有可能anil部分分配,无效,未定义,......除了有效值之外的任何东西?

我试图让它失败,但到目前为止它总是成功(在我的Mac上).

Go Go Memory Model文档中,我无法找到超出此引用的任何特定内容:

大于单个机器字的值的读取和写入表现为以未指定的顺序进行的多个机器字大小的操作.

这是否意味着单个机器字写入实际上是原子的?并且,如果是这样,函数指针写入Go单个机器字操作?

更新:这是一个正确同步的解决方案

concurrency go goroutine

6
推荐指数
2
解决办法
1211
查看次数

Golang concurrency write to variable - why this code works?

I'm learning concurrency-related issues in Golang. I wrote some code:

package main

import (
    "fmt"
    "time"
)

func incr(num *int) {
    *num = *num + 1

}

func main() {
    var a = 0

    for i := 0; i < 50; i++ {
        go incr(&a)
    }

    incr(&a)

    time.Sleep(1 * time.Second)
    fmt.Println(a)
}
Run Code Online (Sandbox Code Playgroud)

The result of this code is: 51

In this code I've declared a variable which I'm increasing in 50 running goroutines. What I've read and unsterstood this code …

concurrency mutex locking shared-memory go

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

标签 统计

concurrency ×2

go ×2

goroutine ×1

locking ×1

mutex ×1

shared-memory ×1