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 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM