多线程控制台输出? [英] Multithreaded console output?

查看:256
本文介绍了多线程控制台输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有多个go-routines去,其中2个或更多的决定他们需要打印出来的东西,他们是否有可能互相打断?

例如:

 包主

导入(
fmt


func main(){
go print()
print()
}

func print(){
for true {
fmt.Print(ABCDEF)
}
}

一次执行程序是否可以开始打印( AB ),另一个执行程序中断( ABABCDEF ABABCDEFCDEF )?

我试着自己运行它并检查输出和它看起来好,但我怎么能确定?

解决方案

是的,尽管你不会看到GOMAXPROCS = 1。当运行更多的goroutine,更大的线条和更多的线程时,它们将显示出来。当写入到stderr时,这是没有缓冲的,因为stdout缓冲区接受短写入的速度足以防止交错。



这就是为什么记录器在日志包有一个内部互斥和缓冲区,以正确序列化调用。


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?

解决方案

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.

这篇关于多线程控制台输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆