Question: ```
package main

import(
    "fmt"
    "time"
)

func main(){
    fmt.Println("1")
    defer fmt.Println("-1")
    go func() { 
        fmt.Println("2")
        defer fmt.Println("-2")
        time.Sleep(9 * time.Second)
    }()
    time.Sleep(1 * time.Second)
    fmt.Println("3")
}

```

Produces the output: 1 2 3 -1
But I would've thought the goroutine's defer would have been called to produce: 1 2 3 -2 -1

In my actual code my goroutine is blocked on a websocket... I suppose I could send a shutdown signal but I haven't yet figured out how to do a wait-on-multiple-objects kind of thing (if it can actually be done in go). I'm currently solving my problem by hoisting the deferred -2 into the main scope.

Is there some trick to defer placement I'm not doing right?

<http://play.golang.org/p/qv8UEuF2Rb>

Answer: 
The process is ending, so the internal function is terminated. Try sleeping at the end of main:

```
func main(){
    fmt.Println("1")
    defer fmt.Println("-1")
    go func() { 
        fmt.Println("2")
        defer fmt.Println("-2")
        time.Sleep(9 * time.Second)
    }()
    time.Sleep(1 * time.Second)
    fmt.Println("3")
    time.Sleep(9 * time.Second)
}

```

<http://play.golang.org/p/Qrtz_0xiRs>

EDIT: as mentioned in the comments, this is not the right approach in general. You should explicitly wait for the goroutine.
Yes, the issue is with goroutine scheduling and is [platform dependent](https://groups.google.com/forum/#!topic/golang-nuts/tGvuvc8Z2IQ). Use [runtime.Gosched](http://golang.org/pkg/runtime/#Gosched) at the end of the function with the goroutine to ensure it gets some cputime. Presently on x86\_64 linux, the code below will produce "3" but without Gosched it produces "1":

```
q = 1
go func() { 
    q = 2
    defer func() { q = 3 }()
}()
runtime.Gosched()
fmt.Println(q)

```

<http://play.golang.org/p/dNFQv9IxXv>