doushi1510 2018-03-17 17:33
浏览 30

Go中用于并行读/写操作的数据类型

I have a scenario where I create a worker pool which has 4 workers. These workers picks up job from a channel and stores the result to the memory. So the worker execute the job and may update the result in parallel. I would like to know which data type is best to save the result as it would be accessed by multiple workers at a time. I would need to use the lock mechanism to achieve this.

The result will be key-value format. So can maps be considered in this scenario.

  • 写回答

2条回答 默认 最新

  • doukuo9116 2018-03-17 19:26
    关注

    Yes, you could use a map for that and you would have to protect it by a mutex.

    I would however suggest that each job contains a result channel where you can input the result of the job. Here a rough sketch of what that would look like:

    playground: note that playground only has one core so the numbers will appear in sequence.

    package main
    
    import (
        "fmt"
        "time"
    )
    
    type job struct {
        a     int
        b     int
        chRes chan int
    }
    
    func main() {
    
        var chIn = make(chan job, 20)
    
        for i := 0; i < 10; i++ {
            go worker(chIn)
        }
    
        for i := 0; i < 100; i++ {
            go func(i int) {
                chRes := make(chan int)
                chIn <- job{
                    a:     i,
                    b:     i,
                    chRes: chRes,
                }
    
                fmt.Println(<-chRes)
            }(i)
        }
    
        // I'm lazy, so here just a sleep so we can see something
        time.Sleep(1 * time.Second)
    }
    
    func worker(ch chan job) {
        for job := range ch {
            job.chRes <- job.a + job.b
        }
    }
    

    -- edit --

    If you device to go with a store instead (which kind of goes against the go mantra share memory by communicating instead of communicate by sharing memory): there is also a sync.Map that is already concurrency safe. No mutex needed.

    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)