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 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?