User Tools

Site Tools


Go threads & channels sample

channels.go
/*
 * Copyright 2019 Oleg Borodin  <borodin@unix7.org>
 */
 
package main
 
import (
    "fmt"
    "time"
)
 
func sender1(c chan string) {
    for i := 0; ; i++ {
        c <- "message 1"
        time.Sleep(time.Millisecond * 100)
    }
}
 
func sender2(c chan string) {
    for i := 0; ; i++ {
        c <- "message 2"
        time.Sleep(time.Millisecond * 200)
    }
}
 
func receiver(c1 chan string, c2 chan string) {
    for {
        select {
            case msg1 := <- c1:
                fmt.Println(msg1)
            case msg2 := <- c2:
                fmt.Println(msg2)
            case <- time.After(time.Millisecond * 70):
                fmt.Println("receive timeout")
        }
    }
}
 
func main() {
    channel1 := make(chan string, 4)
    channel2 := make(chan string, 4)
 
    go sender1(channel1)
    go sender2(channel2)
    go receiver(channel1, channel2)
 
    for {
        time.Sleep(time.Second * 1)
    }
}

Result

$ go run channel.go
message 1
message 2
receive timeout
message 1
receive timeout
message 2
message 1
receive timeout
message 1
receive timeout
^C

$ go build channel
$ daemon -f ./channel
$ ps axlH | grep channel
 1000 72880 61365   0  20  0  102788    2240 uwait    S+    7    0:00.02 ./channel
 1000 72880 61365   0  20  0  102788    2240 uwait    S+    7    0:00.02 ./channel
 1000 72880 61365   0  20  0  102788    2240 uwait    S+    7    0:00.01 ./channel
 1000 72880 61365   0  20  0  102788    2240 uwait    S+    7    0:00.01 ./channel
 1000 72880 61365   0  20  0  102788    2240 uwait    S+    7    0:00.01 ./channel
 1000 72880 61365   0  20  0  102788    2240 uwait    S+    7    0:00.01 ./channel
 1000 72880 61365   0  20  0  102788    2240 uwait    S+    7    0:00.01 ./channel
 1000 72880 61365   0  20  0  102788    2240 uwait    S+    7    0:00.01 ./channel