drlndkhib08556095 2017-05-07 20:14
浏览 15
已采纳

双通道死锁

I'm trying to create a program that send strings to a pool of goroutines (through a channel). Once the goroutine have finish their job, they send some results (through an other channel).

The code is:

package main

import "fmt"
import "os"
import "sync"
import "bufio"

func worker(linkChan <-chan string, outChan chan<- string, wg *sync.WaitGroup, jobId int) {
   defer wg.Done()

   for url := range linkChan {
    // ...
     outChan <- url
   }
}

func main() {
    lCh := make(chan string)
    wg := new(sync.WaitGroup)
    outCh := make(chan string)

    urls := []string{}
    if len(os.Args) > 1 {
        for _, link := range os.Args[1:] {
            urls = append(urls, link)
        }
    } else {
        s := bufio.NewScanner(os.Stdin)
        for s.Scan() {
            urls = append(urls, s.Text())
        }
    }

    num_worker := 10

    for i := 0; i < num_worker; i++ {
        wg.Add(1)
        go worker(lCh, outCh, wg, i)
    }
    for _, link := range urls {
        lCh <- link
    }
    close(lCh)

    for res := range outCh {
        fmt.Printf("%s
", res)
    }
    close(outCh)
    wg.Wait()

}

Running echo "something" | ./main cause a deadlock.

From what I've understood, close(lCh) should stop the for url := range linkChan loop. Am I wrong (it seems so since the code deadlock) ?

How can I resolve this deadlock ?

Thank you for your answers.

  • 写回答

2条回答 默认 最新

  • duanchui1955 2017-05-07 21:01
    关注

    You need to pump the urls in a goroutine, otherwise the outCh will fill up which as you aren't emptying it. This will stall all the workers and it will deadlock.

    So re-arrange the code to look like this

    go func() {
        for _, link := range urls {
            lCh <- link
        }
        close(lCh)
        wg.Wait()
        close(outCh)
    }()
    
    for res := range outCh {
        fmt.Printf("%s
    ", res)
    }
    

    And it will work fine

    Complete code

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵