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 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊