Home > Back-end >  How to run 2 goroutines in a specific order
How to run 2 goroutines in a specific order

Time:01-11

I want to execute 2 goroutines sequentially, one after another.

For example, I have following goroutines called in main function:

go func1()
go func2()

And I want that func1() should first complete its execution and then only func2() should execute, every time when I run my main function.

How can I achieve this ordering in goroutines?

Thanks.

CodePudding user response:

To ensure sequential execution of functions, run the functions in a single goroutine:

go func() {
    func1()
    func2()
}()

CodePudding user response:

If you really want them as separate goroutines (why?) you need to synchronize them. You can use channels, mutexes, or other concurrency primitives. The example below accomplishes that with a signaling channel:

ch := make(chan struct{})
go func() {
  func1()
  close(ch)
}
go func() {
  <-ch
  func2()
}

Playground: https://go.dev/play/p/ZqHz-ILpA2J

EDIT: Following Paul Hankin's advice, using close(ch) instead of ch <- struct{}{} to signal completion.

CodePudding user response:

For squentially running go routine , you should always use sync package

package main

import (
    "fmt"
    "sync"
)

func main() {

    var w sync.WaitGroup

    w.Add(1)
    go fun1(&w)
    w.Wait()
    
    w.Add(1)
    go  fun2(&w)
    w.Wait()


}

func fun1(w *sync.WaitGroup) {
    i:=1000
    for i>0{
        i-=1
    }
    fmt.Println("fun1")
    defer   w.Done()
}

func fun2(w *sync.WaitGroup) {
    fmt.Println("fun2")
    defer w.Done()

}
  •  Tags:  
  • Related