Skip to content

Commit

Permalink
Added part of golang course, channels
Browse files Browse the repository at this point in the history
  • Loading branch information
k8s4 committed Sep 29, 2024
1 parent f6f6513 commit c2fc198
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions examples/golang/05c_channels.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package main

import "fmt"
import "time"
import "runtime"

func readChan(ch chan int) {
value := <-ch
fmt.Println("CHAN VALUE: ", value)
}

func writeChan(ch chan <- int) {
for i := 1; i <= 5; i++ {
ch<- i
}
close(ch)
}

func writeSelect(ch chan<- int) {
ch<- 1
}

func readSelect(ch, quit <-chan int) {
for {
select {
case x := <-ch:
fmt.Println("ch3 = ", x)
case <-quit:
fmt.Println("quit")
return
default:
fmt.Println("default")
}
}
}

func main() {
fmt.Println("START MAIN")
var ch chan int
var ch2 chan int

// Buffered and unbuffered channel
ch = make(chan int, 1)
// ch = make(chan int)

ch<- 77
go readChan(ch)
ch<- 111

time.Sleep(1 * time.Second)

// for
ch2 = make(chan int)
go writeChan(ch2)

for i := range ch2 {
fmt.Println("chan i = ", i)
}

// select
ch3 := make(chan int)
quit := make(chan int)

go readSelect(ch3, quit)

go writeSelect(ch3)
runtime.Gosched()
go writeSelect(quit)


fmt.Println("END MAIN")
}

0 comments on commit c2fc198

Please sign in to comment.