我尝试使用“sync.mutex”保护我的函数,但我发现锁仍然使用调用者来销毁它。
var mutex sync.mutex
这是错误:
//caller use
func a() {
for i := 0; i < 10; i++ {
go b(i)
}
}
//My func
func b(i int) {
mutex.Lock()
fmt.Println(i)
mutex.Unlock()
}
这是成功的,但是破坏了我的封装方法:
//caller use
func a() {
for i := 0; i < 10; i++ {
mutex.Lock()
go b(i)
}
}
//my func
func b(i int) {
fmt.Println(i)
mutex.Unlock()
}
谢谢
最佳答案
The Go Programming Language Specification
An identifier may be exported to permit access to it from another package. An identifier is exported if both:
- the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
- the identifier is declared in the package block or it is a field name or method name.
All other identifiers are not exported.
将函数放在自己的包中,不要导出互斥锁。例如。
package b
import (
"fmt"
"sync"
)
var mutex sync.Mutex
func B(i int) {
mutex.Lock()
fmt.Println(i)
mutex.Unlock()
}
使用,
package a
import "b"
func a() {
for i := 0; i < 10; i++ {
go b.B(i)
}
}
关于go - 在golang中,如何保护自己的锁不被调用者破坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47369397/