douao1854 2017-11-17 01:44
浏览 57
已采纳

为工人goroutine排队项目的正确方法?

I am writing an app that allows users to upload files and queue them for processing. My approach to this is to create a goroutine for processing uploaded files and to use a channel to signal that a new file is ready for processing.

Basically, the processing goroutine does this:

for {
    while itemForProcessing() {
        processNextItem()
    }
    select {
    case <-signalChan:
    case <-stopChan:
        return
    }
}

The code for signaling that a new item is ready for processing looks something like this:

select {
case signalChan <- true:
default:
}

Note that this is a non-blocking send on the channel.

There are three possible scenarios:

  • the processing goroutine is in the select{} block — the first case runs and the next item is processed
  • the processing goroutine is executing processNextItem() — the next item will be processed once processNextItem() returns since the loop condition will be true
  • the processing goroutine has exited the loop but has not yet entered the select{} block

The last scenario will result in a problem. The non-blocking send will not send anything on the channel and the goroutine will wait in the select{} block until something else happens.

How can I avoid this problem? I cannot use a blocking send because the processing goroutine may be running processNextItem(), which would cause the send to block for an extremely long period of time.

  • 写回答

1条回答 默认 最新

  • dongzhen6554 2017-11-17 01:51
    关注

    To avoid a lost signal, use a channel with capacity 1.

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

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页