ruk·si

🐹 Go
Channel Handshake

Updated at 2013-12-10 00:40

Quit channels are used to terminate running goroutines. Sometimes you must terminate running goroutine so handshake quit channel is better.

package main

import (
    "fmt"
    "time"
)

func worker(messageChan chan string, quitChan chan bool) {
    for {
        select {
        case messageChan <- "WORKER MESSAGE!":
        case <-quitChan:
            fmt.Println("START WORKER TERMINATION!")
            quitChan <- true
            return
        }
    }
}

func main() {
    quitChan := make(chan bool)
    messageChan := make(chan string)
    go worker(messageChan, quitChan)
    for i := 5; i >= 0; i-- {
        fmt.Println(<-messageChan)
    }
    time.Sleep(2 * time.Second)

    // Send boolean to start termination and wait termination to finish.
    quitChan <- true
    <-quitChan
    fmt.Println("QUIT OK!")
}