dtcwehta624485 2018-10-17 20:41
浏览 117
已采纳

如何使变量成为线程安全的

I'm relatively new to Go, and I need to make a variable thread-safe. I know in java you can just use the synchronized keyword, but nothing like that seems to exist in go. Is there any way to synchronize variables?

  • 写回答

2条回答 默认 最新

  • dongque1646 2018-10-18 20:28
    关注

    synchronized in Java is a mean to allow only a single thread to execute a code block (at any given time).

    In Go there are numerous constructs to achieve that (e.g. mutexes, channels, waitgroups, primitives in sync/atomic), but Go's proverb is: "Do not communicate by sharing memory; instead, share memory by communicating."

    So instead of locking and sharing a variable, try to not do that but instead communicate the result between goroutines e.g. using channels (so you won't have to access shared memory). For details, see The Go Blog: Share Memory By Communicating.

    Of course there may be cases when the simplest, direct solution is to use a mutex to protect concurrent access from multiple goroutines to a variable. When this is the case, this is how you can do that:

    var (
        mu        sync.Mutex
        protectMe int
    )
    
    func getMe() int {
        mu.Lock()
        me := protectMe
        mu.Unlock()
        return me
    }
    
    func setMe(me int) {
        mu.Lock()
        protectMe = me
        mu.Unlock()
    }
    

    The above solution could be improved in several areas:

    • Use sync.RWMutex instead of sync.Mutex, so that the getMe() may lock for reading only, so multiple concurrent readers would not block each other.

    • After a (successful) locking it is advisable to unlock using defer, so if something bad happens in the subsequent code (e.g. runtime panic), the mutex will still be unlocked, avoiding resource leaks and deadlocks. Although this example is so simple, nothing bad could happen and does not warrant unconditional use of deferred unlocking.

    • It is good practice to keep the mutex close to the data it is ought to protect. So "wrapping" protectMe and its mux in a struct is a good idea. And if we're at it, we may also use embedding, so locking / unlocking becomes more convenient (unless this functionality must not be exposed). For details, see When do you embed mutex in struct in Go?

    So an improved version of the above example could look like this (try it on the Go Playground):

    type Me struct {
        sync.RWMutex
        me int
    }
    
    func (m *Me) Get() int {
        m.RLock()
        m.RUnlock()
        return m.me
    }
    
    func (m *Me) Set(me int) {
        m.Lock()
        m.me = me
        m.Unlock()
    }
    
    var me = &Me{}
    
    func main() {
        me.Set(2)
        fmt.Println(me.Get())
    }
    

    This solution has another advantage: should you need multiple values of Me, it will automatically have different, separate mutexes for each value (our initial solution would require creating separate mutexes manually for each new values).

    Although this example is correct and valid, may not be practical. Because protecting a single integer does not really require a mutex. We could achieve the same using the sync/atomic package:

    var protectMe int32
    
    func getMe() int32 {
        return atomic.LoadInt32(&protectMe)
    }
    
    func setMe(me int32) {
        atomic.StoreInt32(&protectMe, me)
    }
    

    This solution is shorter, cleaner and faster. If you're goal is only to protect a single value, this solution is preferred. If the data structure you ought to protect is more complex, atomic may not even be viable, and using a mutex might be justified.

    Now after showing examples of sharing / protecting variables, we should also give an example what we should aim to achieve to live up to "Do not communicate by sharing memory; instead, share memory by communicating."

    The situation is that you have multiple concurrent goroutines, and you use a variable where you store some state. One goroutine changes (sets) the state, and another reads (gets) the state. To access this state from multiple goroutines, access must be synchronized.

    And the idea is to not have a "shared" variable like this, but instead the state that one goroutine would set, it should "send" it instead, and the other goroutine that would read it, it should be the one the state is "sent to" (or in other words, the other goroutine should receive the changed state). So there is no shared state variable, instead there is a communication between the 2 goroutines. Go provides excellent support for this kind of "inter-goroutine" communication: channels. Support for channels is built into the language, there are send statements, receive operators and other support (e.g. you can loop over the values sent on a channel). For an intro and details, please check this answer: What are golang channels used for?

    Let's see a practical / real-life example: a "broker". A broker is an entity where "clients" (goroutines) may subscribe to receive messages / updates, and the broker is capable of broadcasting messages to subscribed clients. In a system where there are numerous clients that might subscribe / unsubscribe at any time, and there may be a need to broadcast messages at any time, synchronizing all this in a safe manner would be complex. Wisely using channels, this broker implementation is rather clean and simple. Please allow me to not repeat the code, but you can check it in this answer: How to broadcast message using channel. The implementation is perfectly safe for concurrent use, supports "unlimited" clients, and does not use a single mutex or shared variable, only channels.

    Also see related questions:

    Reading values from a different thread

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值