go - 在golang中,如何保护自己的锁不被调用者破坏?

标签 go

我尝试使用“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

Exported identifiers

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/

相关文章:

json - 当左侧部分是数​​字时如何在golang中解码json

for-loop - For loop Increment with a step 不起作用

json - 无法将 json 数据反序列化为结构

go - 如何在 golang 中初始化指向指针的指针?

sockets - 去写套接字 - 无效参数

go - 在 Go 中,是否可以写入控制台并读回?

go - 如何从 golang 中的 gzip 或纯文本阅读器读取?

http - 静态资源的基本身份验证

go - 使用 Alice 和 HttpRouter 的中间件

有 OR 查询的 gorm