dsgsdg206050 2018-03-14 10:05
浏览 21
已采纳

如果调用的函数来自不同的包,如何同步goroutine?

To learn how to build web-app in Go, I have created small web app where I am using Gorilla mux and I have mainly below packages main, handlers, model, structs.

I want to use goroutines while going through documentation I came to know that I need to use sync package along with go fun(). I tried to use as shown below, within the same package and it is working fine. But how to sync goroutine if called function are from diffrent package?

// same package : working
package models

import (
    "fmt"
    "sync"
)

var wg sync.WaitGroup

func Func1() (string, error) {
    lexpiry := ReadDatafrom()
    wg.Add(1)
    go validExp(string(lexpiry))
    ----
    ----
    wg.Wait()
    ----
    return "S/F", err
}

func validExp(lexpiry string) {
    fmt.Println("CHeck Expiry Date")
    wg.Done()
}

But if I need to call a function of different package, of course I can add go keyword before package like: go otherPackage.Function()

But how will I sync it? I mean the function which we are calling with go must have wg.Done()?

// Diffrent package : ? ( need guidance how to achive this )

package handlers

import (
    "fmt"
    "sync"
    "go_mjolnir/models"
    "net/http"
)

var wg sync.WaitGroup

func Func1(w http.ResponseWriter, r *http.Request) {
    lexpiry := ReadDatafrom()
    wg.Add(1)
    go models.ValidExp(string(lexpiry))
    ----
        calling func of model package
    ----
    wg.Wait()
    ----
    // return json response
}

package model
---
---

func validExp(lexpiry string) {
    fmt.Println("CHeck Expiry Date")

    // wg.Done()
    // how to call wg.Done() of handllers packge , is it right way ?
}

can some one guide me on this? How to sync goroutine if called function are from different packages?

  • 写回答

1条回答 默认 最新

  • doublestar2014 2018-03-14 10:41
    关注

    Use a closure:

    package main
    
    import "sync"
    
    func main() {
        wg := &sync.WaitGroup{}
        wg.Add(1)
    
        go func() {
                f() // doesn't matter in which package f is defined.
                wg.Done()
        }()
    
        wg.Wait()
    }
    
    func f() {
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同