dongshan7708 2016-08-07 18:15
浏览 45

具有重复队列结构的工作池

I'm trying make worker pool with looped queue. Is my code idiomatic for Go? And how can I solve concurrent access to *Item? Pool processing 1 item at time and *Item don't shared between workers, but sometimes I need change *Item from main thread. Should I place mutex at every *Item and when I should lock/unlock it? Or maybe some other structure is possible?

var items = make(map[uint8]*Item)

func worker(queue, done chan uint8) {
    for id := range queue {
        item := items[id]

        // get from http request
        n := ...

        if item.Count > n {
            ... // perform some actions with id
        }

        done<- id
    }
}

func dispatcher() {
    queue := make(chan uint8, 100)
    done := make(chan uint8, 100)

    for i := 0; i < 4; i++ {
        go worker(queue, done)
    }

    for id := range jobs {
        queue<- id
    }

    for {
        select {
            case id := <-done:
                queue<- id
            ...
        }
    }
}

And main:

func main() {
    go dispatcher()

    for {
        var id, count uint8
        fmt.Scan(&id, &count)
        // modifying
        items[id].Count = count
    }
}

P.S. Sorry for my bad English.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 nginx中的CORS策略应该如何配置
    • ¥30 信号与系统实验:采样定理分析
    • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
    • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
    • ¥15 php 同步电商平台多个店铺增量订单和订单状态
    • ¥15 关于logstash转发日志时发生的部分内容丢失问题
    • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
    • ¥15 微信会员卡接入微信支付商户号收款
    • ¥15 如何获取烟草零售终端数据
    • ¥15 数学建模招标中位数问题