Thursday, February 29, 2024
HomeSoftware EngineeringThe way to Cease a Goroutine in Golang

The way to Cease a Goroutine in Golang


It’s doable to cease a Goroutine by sending a worth into it through a sign channel:

exit := make(chan bool)
go func() {
    for {
        choose {
        case <- exit:
            return
        default:
            // Carry out some duties
        }
    }
}()

// Exit the Goroutine
exit <- true

As a substitute, you could possibly additionally use a WaitGroup and vary over it:

package deal fundamental
import (
    "fmt"
    "sync"
)
func fundamental() {
    var wg sync.WaitGroup
    c := make(chan bool)
    wg.Add(1)
    go func() {
        defer wg.Finished()
        for b := vary c {
            fmt.Printf("Whats up %tn", b)
        }
    }()
    c <- true
    c <- true
    shut(c)
    wg.Wait()
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments