Skip to content

Instantly share code, notes, and snippets.

@udkyo
Created August 12, 2018 20:51
Show Gist options
  • Save udkyo/a75eccf0b7bccea956746cf3eef69be3 to your computer and use it in GitHub Desktop.
Save udkyo/a75eccf0b7bccea956746cf3eef69be3 to your computer and use it in GitHub Desktop.
Goroutine & channel simple example
// I read some needlessly confusing explanations of channels when I was
// learning go, so I figured I'd post a very straightforward example and
// describe it to death with comments
//
// If anyone ever stumbles across it, I hope it helps :)
package main
import (
"fmt"
"time"
)
func main() {
// You need a channel first
c := make(chan string)
// pass it to some goroutines, let's uses one that ostensibly checks URLs
go check("google.com", c)
go check("microsoft.com", c)
// and another to show whatever output the first two generate
go showResults(c)
// The goroutines trigger and execution immediately proceeds, and this
// app isn't doing anything else, so let's block execution here and let
// the goroutines run a few times
time.Sleep(time.Second * 10)
}
// check 'checks' a URL (but doesn't really, for brevity)
func check(url string, c chan string) {
// it loops forever...
for {
// sends a string to the channel
c <- fmt.Sprintf("%s %s", url, "OK")
// then sleeps for a second
time.Sleep(time.Second * 1)
}
}
// showResults is going to show us our output
func showResults(c chan string) {
// it loops forever...
for {
// and prints whatever gets sent to the channel as it comes in
fmt.Println(<-c)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment