多线程控制台输出?

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年7月31日 05:17:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/31734215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定