dsfsw1233 2014-05-22 02:40
浏览 30
已采纳

GoLang,将资源放回频道,将程序挂起

  for i := 0; i < mr.nMap; i++ {
    DPrintf("worker number is %d
", mr.workerNumber)

    worker_str = <- mr.registerChannel

    DPrintf("Worker_str is %s 
",worker_str)

    args := &DoJobArgs{mr.file,"Map",i,mr.nReduce}
    var reply DoJobReply
    var ret bool
    ret = call(worker_str, "Worker.DoJob", args, &reply)
    if ret  {
        fmt.Println("wk worker done.
")
      fmt.Println(worker_str)
      mr.registerChannel <- worker_str   // <=======stuck here
    } else
    {
      fmt.Println("wk worker fail.
")
    }

    DPrintf("map finished.")

  }

btw, mr is instance of this:

type MapReduce struct {
    nMap            int    // Number of Map jobs
    nReduce         int    // Number of Reduce jobs
    file            string // Name of input file
    MasterAddress   string
    registerChannel chan string
    DoneChannel     chan bool
    alive           bool
    l               net.Listener
    stats           *list.List

    // Map of registered workers that you need to keep up to date
    Workers map[string]*WorkerInfo

    // add any additional state here
    workerNumber    int
}

My code hang when I do this "mr.registerChannel <- worker_str "

I really don't understand why. worker_str is available, and I want to put this resource back after using this worker. Put it back to channel, let next job use available workers.

Why it hang? thanks

  • 写回答

1条回答 默认 最新

  • doukeng1922 2014-05-22 02:51
    关注

    In go, channels can be used for synchronization if they are not buffered. Here, the process that is responsible for consuming the mr.registerChannel is trying to write to it. When you read from, or write to and unbuffered channel, you will wait until there is another process on the other end to write to, or read from the channel, respectively.

    So, when this block attempts to write to the channel, it blocks waiting for someone to read what it wrote. Since this block is also responsible for reading, it will wait forever for itself in a deadlock. You need to either redesign this so that you hand the string back off to something else to read, or you need to use a buffered channel and don't expect to trap on the read line worker_str = <- mr.registerChannel. That would have to be re-written as a for/select or something.

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

报告相同问题?

悬赏问题

  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题