英文:
Multithreaded console output?
问题
如果我有多个Go协程在运行,并且其中2个或更多的协程决定需要打印一些内容,它们是否可能相互中断?
例如:
package main
import (
"fmt"
)
func main() {
go print()
print()
}
func print() {
for true {
fmt.Print("ABCDEF")
}
}
是否可能一个协程开始打印(AB
),另一个协程中断(ABABCDEF
),然后原始协程完成打印(ABABCDEFCDEF
)?
我尝试运行它并检查输出,看起来好像是正确的,但我如何确保?
英文:
If I have multiple go-routines going and 2 or more of them decide they need to print something out, is it possible for them to interrupt each other?
For example:
package main
import (
"fmt"
)
func main() {
go print()
print()
}
func print() {
for true {
fmt.Print("ABCDEF")
}
}
Is it possible for one go-routine to start printing (AB
) and another go-routine interrupting (ABABCDEF
) and the original finishing (ABABCDEFCDEF
)?
I've tried running it myself and checking the output and it looks good, but how can I be sure?
答案1
得分: 4
是的,虽然在使用GOMAXPROCS=1时你看不到任何效果,但是它是可能的。当使用更多的goroutine、更大的行数和更多的线程运行时,你会看到效果。尤其是在写入stderr时,因为它是无缓冲的,stdout缓冲区足够快地接受短写入,以帮助防止交错。
这就是为什么"log"包中的Logger有一个内部互斥锁和缓冲区,以正确地序列化调用。
英文:
Yes, it's possible, though you won't see any with GOMAXPROCS=1. They will show up when running with more goroutines, larger lines, and more threads. Even more so when writing to stderr, which is unbuffered, since the stdout buffer accepts the short writes fast enough to help prevent interleaving.
This is why the Logger in the "log" package has an internal mutex and buffer, to properly serialize the calls.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论