Go worker pool with repetitive queue structure

家住魔仙堡 提交于 2019-12-12 01:45:02

问题


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.

来源:https://stackoverflow.com/questions/38817122/go-worker-pool-with-repetitive-queue-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!