DEV Community

ynwd
ynwd

Posted on

3 2

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.

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay