Home >Backend Development >Golang >Running race conditions

Running race conditions

王林
王林forward
2024-02-08 21:00:041239browse

Running race conditions

Question content

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


Correct answer


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.

There are a lot of options to deal with this, but all of them lead to basically the same result: make sure

is sent on the channel after the function has run, you can do this via a for example (non-exhaustive )

    Defer sending the message before the timer (defer running in reverse order)
  • defer() in sub-function, signal
  • in external function
  • Don't use defer, just run the exit message before sending the signal
  • Instead of sending the message and printing separately, send the runtime of the function over the channel and let the caller format and report

The above is the detailed content of Running race conditions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete