Drew LeSueur
Drew LeSueur

Reputation: 20145

How to get a Go program to block forever

I am trying to get my Go program to block forever, but nothing is working.

Here are some things I have tried:

package main

func main() {
    select{}
}

and

package main

func main() {
    ch := make(chan bool)
    <-ch
}

and

package main

import "sync"

func main() {
    var wg sync.WaitGroup
    wg.Add(1)
    wg.Wait()
}

Each time I get the same error: fatal error: all goroutines are asleep - deadlock!

I thought I have done this before easily. Am I able to get the go program to block forever?

Upvotes: 1

Views: 1028

Answers (3)

Ahui
Ahui

Reputation: 61

For the question "How to get a Go program to block forever" there's already answers that use a for loop or time.Sleep.

But I want to answer "How to get a Go program to block forever with a channel never receives a value".

package main

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

    go func(c chan bool) {
        for {
        }
        c <- true // Because c never receives true,
    }(ch)

    <-ch // thus ch waits forever.
}

I think the sample code above can help to understand why and when a Go program will block by a channel.

Upvotes: 1

peterSO
peterSO

Reputation: 166704

For example, the main goroutine blocks forever,

package main

import (
    "fmt"
    "time"
)

func forever() {
    for {
        fmt.Println(time.Now().UTC())
        time.Sleep(time.Second)
    }
}

func main() {
    go forever()
    select {} // block forever
}

Output:

2017-08-05 02:50:10.138353286 +0000 UTC
2017-08-05 02:50:11.138504194 +0000 UTC
2017-08-05 02:50:12.138618149 +0000 UTC
2017-08-05 02:50:13.138753477 +0000 UTC
2017-08-05 02:50:14.13888856 +0000 UTC
2017-08-05 02:50:15.139027355 +0000 UTC
...
...
...

Upvotes: 3

Ammar Bandukwala
Ammar Bandukwala

Reputation: 1572

Those methods would work if you spawned another goroutine (which was doing stuff other than blocking)

The immediate fix to your problem would be:

time.Sleep(math.MaxInt64)

which would sleep for ~300 years

Upvotes: 4

Related Questions