dongyi1159 2016-11-19 15:38
浏览 35
已采纳

如何在并发环境中每个键参数运行一次golang函数调用?

This example seems to fetch data once, but I don't think it will invoke a fetchDataInBackground function in background for each key concurrently.

func Get(key string){
    ...
    if itIsTheTimeToRefreshData{
         var once sync.Once
         onceBody := func() {
            fetchDataInBackground()
         }
         go func() {
            once.Do(onceBody)
         }()
     }
     ...
 }

what I need to do is to assign each Once instance to a key so that all fetch data for different keys can be done concurrently. how do I do that?

  • 写回答

1条回答 默认 最新

  • dqpu4988 2016-11-19 16:13
    关注

    I think sync.Once is not well for such task. You need to maintain some flag ("once") for each key individually. Map with mutexed access is one of possible solutions.

    Full working example:

    package main
    
    import (
            "fmt"
            "sync"
            "time"
    )
    
    var once map[string]bool
    var onceMutex sync.Mutex
    var itIsTheTimeToRefreshData = true
    
    func Get(key string) {
            fmt.Printf("Access for key: %s
    ", key)
            if itIsTheTimeToRefreshData {
                    onceBody := func() {
                            fmt.Printf("Only once for key: %s
    ", key)
                            //fetchDataInBackground()
                    }
    
                    onceMutex.Lock()
                    if !once[key] { // is it first time?
                            once[key] = true
                            onceMutex.Unlock()
    
                            // refresh something here
                            go onceBody()
                    } else {
                            onceMutex.Unlock()
                    }
            }
    }
    
    func main() {
            once = make(map[string]bool)
    
            // do it first time in parallel
            for i := 0; i < 10; i++ {
                    key := fmt.Sprintf("i%d", i)
                    go func(key string) {
                            Get(key)
                    }(key)
            }
            // and another time
            for i := 0; i < 10; i++ {
                    key := fmt.Sprintf("i%d", i)
                    go func(key string) {
                            Get(key)
                    }(key)
            }
            fmt.Println("All requested.")
            time.Sleep(1 * time.Second)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗