package main

import "time"
import "fmt"

var index int64

func increase(){
  index++
}

func read(){
  fmt.Println(index)
}

func main(){
   go func(N int){
     for i:=0; i < N; i++{
        increase()
        time.Sleep(500 * time.Millisecond)
     }
 }(5)
   time.Sleep(2 * time.Second)
   read()
}


在2022年4月30日星期六 UTC+8 13:49:11<Zhaoxun Yan> 写道:

> point race means I/O on a global might clash at certain point of time.
>
> consider this example:
>
> package main
>
> import "time"
> import "fmt"
>
> var index int64
>
> func increase(){
>   index++
> }
>
> func read(){
>   fmt.Println(index)
> }
>
> func main(){
>    go func(N){
>      for i:=0; i < N; i++{
>         increase()
>         time.Sleep(500 * time.Millisecond)
>      }
>  }(5)
>    time.Sleep(2 * time.Second)
>    read()
> }
>
> Obviously, the increase function is writing the global variable 'index' 
> while the read is reading it. It is highly unlikely that they could 
> function at the same time, but not impossible.  Further, if the increase 
> function takes longer time to manipulate the global, such as an array which 
> might enlarge itself, and reading during the changing of the global is 
> dangerous. 
>
> The code in my project has a little variation -  the writing of the 
> variable is controlled by crontask of "github.com/robfig/cron". However, 
> the essence is the same. Point-time race condition is undetectable by `go 
> build race`. Thanks to Rust on emphasizing the single entrance to any 
> variable,  I realized this possibility and have to add sync.Mutex to both 
> functions. 
>
> What is your opinion?
>  
> Best Regards,
>   Zhaoxun
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/d6667b87-3ef9-4cff-b63d-aaef8b035ea3n%40googlegroups.com.

Reply via email to