Home >Backend Development >Golang >Running race conditions
When the code is running, sometimes the time spent in the attack() function is printed I know they are race conditions when an attack writes to a channel and the main reads it and then the main exits without waiting for the timer ("attack") to execute
I am new here:_)
package main import ( "fmt" "time" ) func timer(funcName string) func(){ startTime := time.Now() return func(){ fmt.Printf("%s took %v time to run \n", funcName, time.Since(startTime)) } } func main(){ defer timer("main")() smokeSignal := make(chan bool) evilNinga := "Tommy" go attack(evilNinga, smokeSignal) fmt.Println(<-smokeSignal) } func attack(target string, smokeSignal chan<-bool){ defer timer("attack")() time.Sleep(time.Second) fmt.Println("Throwing ninja stars at ", target) smokeSignal <- true }
Can someone tell me how to handle this situation, I want to print the time taken by both functions and use the channel
when## When #main exits, the program will terminate, concurrent goroutines will not terminate gracefully (in many programs, non-main goroutines are secondary "daemons" that are not shut down at all), so there is no guarantee that existing defers will run. That's what happens here: when you send a smoke signal, if the
attack goroutine is descheduled, then main can return before being rescheduled, so
defer never runs.
is sent on the channel after the function has run, you can do this via a for example (non-exhaustive )
The above is the detailed content of Running race conditions. For more information, please follow other related articles on the PHP Chinese website!