Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do I have to wrap a function with goroutine to use timeout?

So, basically, is there any difference between these 2 blocks of code?

res := make(chan error, 1)
go func() {
        res <- slowOperation()
}()
select {
    case <-time.After(deadline):
        return errors.New("deadline exceeded")
    case err := <-res:
        return err
}

and

res := make(chan error, 1)

select {
    case <-time.After(deadline):
        return errors.New("deadline exceeded")
    case res <- slowOperation():
        err := <-res
        return err
}

Is it necessary to wrap a function in goroutine, as all of the examples on the Internet show, and if so, why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, there is a significant difference between the two blocks of code.

In the first block of code, you are creating a goroutine using go func() { ... }() to run slowOperation() asynchronously. The select block will wait for either the slowOperation() to complete or the deadline to be exceeded. If the deadline is exceeded, the function returns an error; otherwise, it returns the result of slowOperation().

In the second block of code, you are not using a goroutine to run slowOperation(); instead, it runs synchronously within the select block. This means that the time.After(deadline) case will not be evaluated until slowOperation() has completed, which effectively removes the deadline functionality.

In conclusion, using a goroutine is necessary when you want to execute a function asynchronously and evaluate multiple channels simultaneously in the select block, as shown in the first block of code.

Hoping it can help you.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading