本文介绍了问题与runtime.LockOSThread()和runtime.UnlockOSThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个类似的代码,例如 $ p $ 例程1 { runtime.LockOSThread() print 将int发送到例程2 runtime.UnlockOSThread } 例程2 { runtime.LockOSThread()打印一些东西发送int到例程1 runtime.UnlockOSThread } main { go例程1 使用运行时锁定解锁,因为我不使用运行时锁定解锁想要打印例程1将与例程2混合。但是,在执行上述代码之后,输出与没有锁定解锁(意味着打印输出混合)相同。任何人都可以帮我解释为什么会发生这种情况,以及如何强迫这种情况发生。 注意:我给出了一些打印的例子,但是有很多打印和发送事件。 解决方案如果您想要序列化 ,例如每个打印的东西都应该以原子方式执行,然后只是序列化。 你可以通过互斥量包围打印某些东西。这将工作,除非代码死锁,因为这 - 当然它很容易可以在一个不平凡的程序。 在序列化的东西的简单方法是做到这一点与一个频道。收集所有应该一起打印的(去)例程。当完成打印单元的收集时,通过通道将其作为打印作业单元发送给某个打印代理。该代理将仅收到其任务并原子打印每一个。一个人可以免费获得这种原子性,并且作为一个重要的奖励,代码不会在简单的情况下轻易死锁,只有非独立的印刷单元生成goroutine。 我的意思是: func printer(任务chan字符串){ for s:= range tasks { fmt.Printf(s)} } func someAgentX(任务chan字符串){ var printUnit字符串 //。 .. 任务< - printUnit // ... } func main(){ // ... 任务:= make(chan string,size)去打印机(任务)去someAgent1(任务) // ... 去someAgentN(任务) // ... 关闭(任务)} I have a code like,Routine 1 {runtime.LockOSThread()print somethingsend int to routine 2runtime.UnlockOSThread}Routine 2 {runtime.LockOSThread()print somethingsend int to routine 1runtime.UnlockOSThread}main {go Routine1go Routine2}I use run time lock-unlock because, I don't want that printing ofRoutine 1 will mix with Routine 2. However, after execution of abovecode, it outputs same as without lock-unlock (means printing outputsmixed). Can anybody help me why this thing happening and how to forcethis for happening.NB: I give an example of print something, however there are lots ofprinting and sending events. 解决方案 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)} 这篇关于问题与runtime.LockOSThread()和runtime.UnlockOSThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-24 09:11