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() {
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?