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 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持