Created
May 30, 2014 12:29
-
-
Save feyeleanor/ffd6d6ed5b32184c7281 to your computer and use it in GitHub Desktop.
Goroutine launch puzzler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
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 _