英文:
Are function variables concurrency-safe in golang?
问题
我有以下类型声明:
type TestFn func(id int, ctx context.Context) error
var Func1 = TestFn(func(id int, ctx context.Context) error {
// 做一些工作 - 执行块是并发安全的
})
var Func2 = TestFn(func(id int, ctx context.Context) error {
// 做一些工作
})
var Func3 = TestFn(func(id int, ctx context.Context) error {
// 做一些工作
})
func Execute() {
for i := 0; i < 5; i++ {
go Func1(i, ctx)
go Func2(i, ctx)
go Func3(i, ctx)
}
}
由于Func1
、Func2
和Func3
是全局变量,并且被赋值为函数,我可以在多个goroutine中使用不同的参数运行相同的函数吗?
英文:
I have following types declared
type TestFn func(id int, ctx context.Context) error
var Func1 = TestFn(func(id int, ctx context.Context) error {
// do some work -- the execution block is concurrent safe
}
var Func2 = TestFn(func(id int, ctx context.Context) error {
// do some work
}
var Func3 = TestFn(func(id int, ctx context.Context) error {
// do some work
}
func Execute()
for i := 0; i < 5; i++ {
go Func1(i, ctx)
go Func2(i, ctx)
go Func3(i, ctx)
}
}
As Func1
, Func2
, Func3
are global variables and assigned to functions, can I run same function in multiple go routines with different params?
答案1
得分: 3
规则很简单:在至少有一个访问是写操作的情况下,没有任何值可以在多个goroutine之间进行并发访问(无需同步)。
你的示例只读取函数变量,所以是安全的。如果有一个goroutine与Execute()
的执行同时运行,并修改函数变量,那就不安全了。但是在你的示例中并没有发生这种情况。
注意:你的函数变量当然是在包初始化期间写入的。这发生在main()
开始之前的单个goroutine中。
英文:
The rule is simple: no value is safe for concurrent access from multiple goroutines (without synchronization) where at least one of the accesses is a write.
Your example only reads the function variables, so it is safe. If there would be a goroutine running concurrently with the execution of Execute()
that would modify the function variables, that would not be safe. But this doesn't happen in your example.
Note: your function variables are of course written once, during package initialization. That happens in a single goroutine before main()
starts.
答案2
得分: -1
是的,你的代码有效。
如果一个goroutine尝试在另一个goroutine尝试启动相同的FuncXX
时重新分配FuncXX
的值,那么你可能会遇到问题,这将导致竞态条件。
英文:
Yes, your code works.
You would have issues if a goroutine tried to reassign the value of FuncXX
while another one tries to start that same FuncXX
-- this would be a race condition.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论