普通网友 2014-04-05 20:48
浏览 135

如何处理goroutine中的错误?

I'm trying to run several tasks concurrently and get the result or error back.

//data channels
    ch := make(chan int)
    ch2 := make(chan int)
    ch2 := make(chan int)
//error channels 

   errCh := make(chan error)
    errCh2 := make(chan error)
    errCh3 := make(chan error)

 //functions 
        go taskF(ch, errCh)
        go taskF2(ch2, errCh2)
        go taskF3(ch3, errCh3)

Then I start checking on each error. If there is any error we print it otherwise we print the result of each task

      err := <-errCh
      if err != nil{
           print('we have an error ')
       return  
  }
          err2 := <-errCh2
          if err2 != nil{
           print('we have an error 2')
           return  
  }
       err3 := <-errCh3
      if err3!= nil{
           print('we have an error 3')
           return   
 }

Then if there is no error I collect the values returned though each channel

task := <-ch
task2 := <-ch2
task3 := <-ch3

print("task %v task2 %v task3 %v", task, task2, task3)

I'm wondering if I'm doing it right. I'm worried that the code quite verbose. I was thinking to use buffered channels for errors but i can't figure it out how to check all the errors. I think it would also be nice to somehow sync the errors within the goroutines so that if there is an error on one goroutine the other goroutines would stop but I don't know any way to do in an unblocking manner.

  • 写回答

1条回答 默认 最新

  • doubingling4706 2014-04-05 22:09
    关注

    Consider using only one channel for synchronization, and having this channel include an error state (see the Result struct). Whenever you receive a Result, make sure the error state is nil. Wrapping each task in a Task struct will allow you to call Stop on each task when one returns an error. Depending on your exact application there may be better ways to handle this, such as WaitGroups (http://golang.org/pkg/sync/#WaitGroup).

    type Result struct {
        Val int
        Err error
    }
    type Task struct {
         stopped bool
    }
    
    func (t *Task) Stop() {
         t.stopped = true
    }
    func (t *Task) Run(doneChan chan Result) {
        // long-running task here
        // periodically check t.stopped
        doneChan <- Result{Val: ..., Err: nil}
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图