2

EDIT: My question is different from How to write my own Sleep function using just time.After? It has a different variant of the code that's not working for a separate reason and I needed explanation as to why.

I'm trying to solve the homework problem here: https://www.golang-book.com/books/intro/10 (Write your own Sleep function using time.After).

Here's my attempt so far based on the examples discussed in that chapter:

package main

import (
        "fmt"
        "time"
)

func myOwnSleep(duration int) {
        for {
                select {
                case <-time.After(time.Second * time.Duration(duration)):
                        fmt.Println("slept!")
                default:
                        fmt.Println("Waiting")
                }
        }
}

func main() {
        go myOwnSleep(3)

        var input string
        fmt.Scanln(&input)
}

http://play.golang.org/p/fb3i9KY3DD

My thought process is that the infinite for will keep executing the select statement's default until the time.After function's returned channel talks. Problem with the current code being, the latter does not happen, while the default statement is called infinitely.

What am I doing wrong?

Community
  • 1
  • 1
pardonmemiss
  • 149
  • 1
  • 1
  • 11
  • 2
    Related: [How to write my own Sleep function using just time.After?](http://stackoverflow.com/questions/31942163/how-to-write-my-own-sleep-function-using-just-time-after) – icza Oct 04 '15 at 20:16
  • Yes, I was trying to comment there with question about my version of the code but didn't have enough rep :) – pardonmemiss Oct 04 '15 at 20:21

1 Answers1

6

In each iteration of your for loop the select statement is executed which involves evaluating the channel operands.

In each iteration time.After() will be called and a new channel will be created!

And if duration is more than 0, this channel is not ready to receive from, so the default case will be executed. This channel will not be tested/checked again, the next iteration creates a new channel which will again not be ready to receive from, so the default case is chosen again - as always.

The solution is really simple though as can be seen in this answer:

func Sleep(sec int) {
    <-time.After(time.Second* time.Duration(sec))
}

Fixing your variant:

If you want to make your variant work, you have to create one channel only (using time.After()), store the returned channel value, and always check this channel. And if the channel "kicks in" (a value is received from it), you must return from your function because more values will not be received from it and so your loop will remain endless!

func myOwnSleep(duration int) {
    ch := time.After(time.Second * time.Duration(duration))
    for {
        select {
        case <-ch:
            fmt.Println("slept!")
            return // MUST RETURN, else endless loop!
        default:
            fmt.Println("Waiting")
        }
    }
}

Note that though until a value is received from the channel, this function will not "rest" and just execute code relentlessly - loading one CPU core. This might even give you trouble if only 1 CPU core is available (runtime.GOMAXPROCS()), other goroutines (including the one that will (or would) send the value on the channel) might get blocked and never executed. A sleep (e.g. time.Sleep(time.Millisecond)) could release the CPU core from doing endless work (and allow other goroutines to run).

Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827
  • Thanks for the inputs! I just tried with removing the `for` loop (http://play.golang.org/p/BU3qGK8hLJ), could you explain why it still gets stuck at `Waiting` and does not move onto the channel completion case? How do I make it "listen to the event" of channel talking? – pardonmemiss Oct 04 '15 at 20:25
  • Ah, in the other answer you had linked to, this line really helps clarify it: "So just receive a value from the returned channel, and the receive will block until the value is sent:" (I still wouldn't mind my question in the comment above being answered) – pardonmemiss Oct 04 '15 at 20:26
  • @pardonmemiss See edited answer. I included how to fix your function. – icza Oct 04 '15 at 20:30
  • Yep! That return made all the difference. Thanks for the caution about the Single threaded machines; I'll be careful before I run code like this on VMs! – pardonmemiss Oct 04 '15 at 20:45