DEV Community

ynwd
ynwd

Posted on

3 1

Data Races di Golang: Fixing with Channels

Pada artikel sebelumnya, kita telah memperbaiki data race dengan WaitGroup.

Kali ini kita akan mencegah data race menggunakan channel.

Caranya sangat mudah.

package main

import (
    "fmt"
)

func getText() string {
    t := "hi"
    done := make(chan bool)

    // go routine #2
    go func() {
        t = "hello"
        done <- true
    }()

    <-done
    return t
}

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

Enter fullscreen mode Exit fullscreen mode

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

Jalankan dengan -race:

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

Dan warning DATA RACE pun tidak muncul lagi.

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

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

Okay