douwen3836 2014-09-11 01:30
浏览 24
已采纳

如何检查goroutine是否成功创建?

In Go, go is the keyword to spawn a goroutine. However, it seems the keyword doesn't return any value, so how could I detect if the goroutine is spawned correctly?

It seems Go uses the following ways to check whether a func is successful or not.

value, err = myFunc(value)

Is there a similar usage for the go keyword to detect a creation error? It seems go will throw a runtime exception if it failed.

I want to make a test to find out the maximum number of goroutine I could create for a CPU.

  • 写回答

3条回答 默认 最新

  • dongqixian8474 2014-09-11 02:09
    关注

    As you already know:

    value, err = myFunc(value)

    is the idiomatic way to handle exceptions by returning the built-in error type. In a way you can compare it to a checked exception, I guess. In your case though, failing to spawn a new goroutine is more of a runtime exception. How golang handles those is by using panics. You can handle them in your code with the built-in recover() function, which will try to regain control of the execution flow. Without that the panic will go up the stack until it crashes the program.

    Notice that recover() has to be called in a function which is being defered, those functions are pushed into a list and are always called at the end of the function in which they were defered - so even when the panic occurs they will be called, allowing you to call recover(). If you just try to call recover() at the end of your function (or well anywhere after you panicking subfunction) the execution will never reach it. If you can handle the panic (recover() doesn't return an err) so that your program can actually continue it will execute from the point where the function that threw the panic was.

    Think the above blog post is enough but if you need more examples just comment here.

    Also your system will most probably be bounded by RAM memory rather than CPU.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 帮写一个c语言黑白棋代码,必须c语言
  • ¥15 一个小程序关于简单的增删改查
  • ¥15 公司内网,想基本不写代码挂一些视频,有一个还不错的前端展示,有什么软件或者框架可以用吗?尽量简单
  • ¥15 appium自动化测试
  • ¥30 java怎么解析CanFD的16进制数据
  • ¥15 广义可加模型和光滑曲线拟合的R代码
  • ¥15 编写泥浆密度在管路中变化,管路瞬变流计算根据上述描述表示泥浆密度沿着管路的长度方向在不断变化,如何来表示泥浆密度随管路流速的变化
  • ¥15 关于C#多个文本框输入的问题
  • ¥15 手机接Usb hub再连接电脑下D+D-波形
  • ¥20 有谁可以帮我运行一个线搜索回退法程序,有偿