dongpo7467 2013-12-11 12:12
浏览 112
已采纳

从goroutine写入STDOUT时避免混乱的输出

When writing to stdout or a log, how can I make sure that the output from several goroutines aren't messing up the output?

e.g. make sure the output will be like this

Routine 1 found 1235 entries
Routine 3 found 999 entries
Routine 2 found 24 entries

and NOT like this

Routine 1 fouRoutine 3 found 999 entries
nd 1235 entriRoutine 2 found 24 entries
es

I mean the output from one goroutine is not writing at the same time as another

i.e. is there a library or a standard way to get a semaphore around the output?

  • 写回答

1条回答 默认 最新

  • dongmacuo1193 2013-12-11 12:18
    关注

    Use the log package for logging. From log.Logger:

    A Logger represents an active logging object that generates lines of output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.

    The fmt package is generally not safe to use with more than one goroutine.

    If time (synchronizing of lock) is of concern, prepend the log statement with go:

    go log.Println("some log")
    

    Note however, that the log output then may be (most certainly) delayed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面