Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
package main
  
import (
  "fmt"
)

func main(){

  //run in background
  go count("sheep")

  go count("fish")

  //wait for keyboard press before exiting
  fmt.Scanln()

}

func count(thing string) {
  for i:=0; true; i++ {
    fmt.Println(i, thing)
    time.Sleep(time.Millisecond * 500)
  }
}


Using Channels

Channels are blocking

Code Block
package main

import (
  "fmt"
  "time"
)

func main(){

  //make channel of type string
  c := make(chan,string)	

  //run in background
  go count("sheep", c)

  //block until message is pushed to the channel
  msg:= <- c

  fmt.Println(msg)
}

func count(thing string, c chan string) {
  for i:=0; i <= 5; i++ {
    //send message on channel
    c <- thing
    time.Sleep(time.Millisecond * 500)
  }
} 

In the above code, the program exits once the count routine returns a message on the channel.


References

...