Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interrupt a sleeping goroutine?

Tags:

go

Is there a way in which I can execute, for example

time.Sleep(time.Second * 5000) //basically a long period of time

and then "wake up" the sleeping goroutine when I wish to do so?

I saw that there is a Reset(d Duration) in Sleep.go but I'm unable to invoke it.. Any thoughts?

like image 226
Aniruddh Chaturvedi Avatar asked Apr 28 '14 01:04

Aniruddh Chaturvedi


People also ask

How do you signal a Goroutine to stop?

Typically, you pass the goroutine a (possibly separate) signal channel. That signal channel is used to push a value into when you want the goroutine to stop. The goroutine polls that channel regularly. As soon as it detects a signal, it quits.

Is time sleep blocking Golang?

So no, time. Sleep does not block the goroutine. The problem is "block goroutine" is not something with a defined meaning.

How does sleep work in Golang?

The sleep function from the time package is used to pause the execution of the current thread for a particular duration of time. This can be helpful when you are performing some asynchronous activity and want to wait for a few seconds before executing some code.


1 Answers

There isn't a way to interrupt a time.Sleep, however, you can make use of time.After, and a select statement to get the functionality you're after.

Simple example to show the basic idea:

package main

import (
    "fmt"
    "time"
)

func main() {
    timeoutchan := make(chan bool)

    go func() {
        <-time.After(2 * time.Second)
        timeoutchan <- true
    }()

    select {
    case <-timeoutchan:
        break
    case <-time.After(10 * time.Second):
        break
    }

    fmt.Println("Hello, playground")
}

http://play.golang.org/p/7uKfItZbKG

In this example, we're spawning a signalling goroutine to tell main to stop pausing. The main is waiting and listening on two channels, timeoutchan (our signal) and the channel returned by time.After. When it receives on either of these channels, it will break out of the select and continue execution.

like image 170
Greg Avatar answered Oct 09 '22 21:10

Greg