dream07769 2018-10-09 09:46
浏览 64
已采纳

Golang线程并非每次都执行[重复]

This question already has an answer here:

So, I am testing Golang. I understand fmt.Println is not thread safe. So, I was trying out sync.Mutex. The following is the program:

func threder(mux *Mutex, i int) {
    mux.Lock()
    fmt.Println("I am thread: ", i)
    mux.Unlock()
    return
}

func main() {
    m := &Mutex{}
    for i := 0; i < 300; i++ {
        go threder(m, i)
    }
}

I am expecting 300 lines of output. But, I am getting 80-90 lines. Where am I wrong?

</div>
  • 写回答

1条回答 默认 最新

  • duanliang1999 2018-10-09 09:49
    关注

    When your main returns, all other threads are killed. As your main returns right after starting all threads, some of them don't get to print. You can use sync.WaitGroup to wait for all threads to stop:

    func main() {
        m := &sync.Mutex{}
        var wg sync.WaitGroup
        for i := 0; i < 300; i++ {
            wg.Add(1)
            go func(i int) {
                defer wg.Done()
                threder(m, i)
            }(i)
        }
        wg.Wait()
    }
    

    About your comment: If you do not pass the sync.Mutex as a pointer, but the value, to the function the sync.Mutex will be copied and each copy will operate independently of each other. Therefore there will be no synchronization between threads, as they all use their own, independent sync.Mutex. Also, you must not copy a sync.Mutex after the first use, as stated in the docs. This would not happen in your case, as you copy before using the sync.Mutex, but be aware of it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 github符合条件20分钟秒到账,github空投 提供github账号可兑换💰感兴趣的可以找我交流一下
  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?