Running race conditions

王林
Release: 2024-02-08 21:00:04
forward
1188 people have browsed it

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!