Data Races di Golang: Fixing with WaitGroup

ynwd

ynwd

Posted on November 11, 2021

Data Races di Golang: Fixing with WaitGroup

Pada artikel sebelumnya, telah kita bahas data races di golang. Kali ini kita akan mencegahnya agar tidak terjadi menggunakan sync.WaitGroup.

Caranya cukup mudah.

package main

import (
    "fmt"
    "sync"
)

func getText() string {
    t := "hi"
    var waitgroup sync.WaitGroup
    waitgroup.Add(1)

    // go routine #2
    go func() {
        t = "hello"
        waitgroup.Done()
    }()

    waitgroup.Wait()
    return t
}

// go routine #1
func main() {
    fmt.Println(getText())
}

Enter fullscreen mode Exit fullscreen mode

Source code: https://play.golang.org/p/lYasbbWmB0j

Jalankan dengan -race:

$ go run -race main.go                                                                                  main*
hello
Enter fullscreen mode Exit fullscreen mode

Dan warning DATA RACE pun tidak muncul lagi.

💖 💪 🙅 🚩
ynwd
ynwd

Posted on November 11, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related