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: 
(I don't have enough reps to comment?)

> 
> Yes, the issue is with goroutine scheduling and is platform dependent. Use 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":
> 
> 
> 

No. That's not the issue, and that only solves it by co-incidence(via an implementation detail). As has already been hinted at in [goroutine's defer not called when main scope ends](https://stackoverflow.com/questions/19613931/goroutines-defer-not-called-when-main-scope-ends/19614010#19614010) . Your code is racy and you must therefore *explicitly* synchronize the goroutines. The simplest way is to to use a channel or a waitgroup <http://golang.org/pkg/sync/#WaitGroup> . Which option is more appropriate depends on what you're doing. If all you want to do is wait for some result, then have the gorutine send its result on the channel and you simply wait for it. If you just want to wait for a number of goroutines, then use a waitgroup.
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.