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 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错