Skip to content

Instantly share code, notes, and snippets.

@feyeleanor
Created May 30, 2014 12:29
Show Gist options
  • Save feyeleanor/ffd6d6ed5b32184c7281 to your computer and use it in GitHub Desktop.
Save feyeleanor/ffd6d6ed5b32184c7281 to your computer and use it in GitHub Desktop.
Goroutine launch puzzler
package main
import (
. "fmt"
. "net/http"
)
const ADDRESS = ":1024"
const SECURE_ADDRESS = ":1025"
func main() {
message := "hello world"
HandleFunc("/hello", func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Type", "text/plain")
Fprintf(w, message)
})
Spawn(
func() { ListenAndServe(ADDRESS, nil) },
func() { ListenAndServeTLS(SECURE_ADDRESS, "cert.pem", "key.pem", nil) },
)
}
func Spawn(f ...func()) {
done := make(chan bool)
for _, s := range f {
go func() {
s()
done <- true
}()
}
for l := len(f); l > 0; l-- {
<- done
}
}
package main
import (
. "fmt"
. "net/http"
)
const ADDRESS = ":1024"
const SECURE_ADDRESS = ":1025"
func main() {
message := "hello world"
HandleFunc("/hello", func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Type", "text/plain")
Fprintf(w, message)
})
Spawn(
func() { ListenAndServe(ADDRESS, nil) },
func() { ListenAndServeTLS(SECURE_ADDRESS, "cert.pem", "key.pem", nil) },
)
}
func Spawn(http, https func()) {
done := make(chan bool)
go func() {
http()
done <- true
}()
go func() {
https()
done <- true
}()
<- done
<- done
}
@wlaurance
Copy link

This took me a little while to figure out. The issue is that the function doesn't have a closure over the function s.

Try changing the body of the for loop in "This doesn't" to something like this.

  for _, s := range f {
    a := func(fun func()) {
      fun()
      done <- true
    }
    go a(s)
  }

Go doesn't capture external variables.

Here is a better explanation that I found https://code.google.com/p/go-wiki/wiki/CommonMistakes

Edit: Changed i back to _

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment