duai4512 2011-12-04 19:46
浏览 65
已采纳

与runtime.LockOSThread()和runtime.UnlockOSThread有关的问题

I have a code like,

Routine 1 {
runtime.LockOSThread()
print something
send int to routine 2
runtime.UnlockOSThread

}

Routine 2 {
runtime.LockOSThread()
print something
send int to routine 1
runtime.UnlockOSThread

}


main {
go Routine1
go Routine2
}

I use run time lock-unlock because, I don't want that printing of Routine 1 will mix with Routine 2. However, after execution of above code, it outputs same as without lock-unlock (means printing outputs mixed). Can anybody help me why this thing happening and how to force this for happening.

NB: I give an example of print something, however there are lots of printing and sending events.

  • 写回答

3条回答 默认 最新

  • doujun7161 2011-12-04 21:12
    关注

    If you want to serialize "print something", e.g. each "print something" should perform atomically, then just serialize it.

    You can surround "print something" by a mutex. That'll work unless the code deadlock because of that - and surely it easily can in a non trivial program.

    The easy way in Go to serialize something is to do it with a channel. Collect in a (go)routine everything which should be printed together. When collection of the print unit is done, send it through a channel to some printing "agent" as a "print job" unit. That agent will simply receive its "tasks" and atomically print each one. One gets that atomicity for free and as an important bonus the code can not deadlock easily no more in the simple case, where there are only non interdependent "print unit" generating goroutines.

    I mean something like:

    func printer(tasks chan string) {
            for s := range tasks {
                    fmt.Printf(s)
            }
    }
    
    func someAgentX(tasks chan string) {
            var printUnit string
            //...
            tasks <- printUnit
            //...
    }
    
    func main() {
            //...
            tasks := make(chan string, size)
            go printer(tasks)
            go someAgent1(tasks)
            //...
            go someAgentN(tasks)
            //...
            <- allDone
            close(tasks)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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