Various ways to pause code execution

These two goroutines seems to do the exact same thing:

goroutine 1:

	go func() {
		time.Sleep(50 * time.Millisecond)
        // Code that needs to be executed in 50 ms
	}()

goroutine 2:

	go func() {
		select {
		case <-time.After(50 * time.Millisecond):
			// Code that needs to be executed in 50 ms
		}
	}()

The syntax in the second goroutine is, in my opinion, horrible. It is harder to read, unless you have seen it before and recognize it, and it is longer to type. Is there a difference between them? Is there even a reason to “memorize” the second way of pausing execution (goroutine 2)?

I would use the first. The second only makes sense if you have some other channel receive in the select, e.g. perform some operation and time it out after 50ms.

3 Likes

Those are different things. The first one is sleeping (and is blocked completely), while the second is waiting. You could add another case with waiting on the second channel (for example for case <-context.Done():, and interrupt this “sleeping” (which in reality is waiting), or that another channel could be an OS signal handling.

1 Like

@skillian Ok, so the difference is mainly about channels then. That makes sense, I have barely scratched the surface of channels yet, so that is why I did not see that.

@kron4eg Is there a practical difference between sleeping and waiting, when the second goroutine is not doing anything other than waiting? Doesn’t that mean that goroutine 2 is practically blocked as well?

Of course if you use just 1 case with case <-time.After(): that’s practically the same. And in such case you should use time.Sleep().

1 Like

It would be fine to simply wait for the first one to be used, but the second one can wait for other chan, and use’case After’ as a timeout.

Use option 2, because:

  • it is easier to add a second case to cancel the wait
  • uses less resources as time.Sleep (not sure though, please someone who knows how time.Sleep works elaborate)
  • the syntax communicates intent in a clearer way; my opinion seems counter intuitive but this is standard syntax (working with channels and synchronization, time.Sleep looks really bad for me)
  • you get a better chance to actually wait for 50 milliseconds and not more

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.