简体   繁体   中英

What's the difference between Data Race and Condition in Go?

Hi i'm new in go and i currently still learning on it, there is a question about the difference between data race and race condition, i get a bit confused about the difference between it and can someone tell me what is the real different between those condition and the sample answer? Thanks in advance

A data race is where a variable is written concurrently with other reads and writes of the variable. Here's a data race example:

 x := 1
 go func() { x = 2 }()  // The write to x on this line executes ...
 fmt.Println(x)         // concurrently with the read on this line

The program can print 1, 2, or fail in some unspecified way.

A race condition is where concurrently executing code produces different results due to timing. Here's a race condition example:

 ch := make(chan int, 1)
 go func() { ch <- 1 }()
 go func() { ch <- 2 }()
 fmt.Println(<-ch)

The goroutines race to send a value to the channel. The program can print 1 or 2.

A data race is a kind of race condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM