Skip to content

Commit

Permalink
add channel for week3
Browse files Browse the repository at this point in the history
  • Loading branch information
huangchuan committed May 9, 2022
1 parent 70c27f0 commit c5cd98c
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
31 changes: 31 additions & 0 deletions week3-channeel/channel_select.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

import (
"log"
"time"
)

func main() {
ch1 := make(chan int)
ch2 := make(chan int)
go func() {
time.Sleep(3 * time.Second)
ch1 <- 1
}()

go func() {
time.Sleep(3 * time.Second)
ch2 <- 2
}()

select {
case <-ch1:
log.Println("can read from ch1")
case <-ch2:
log.Println("can read from ch2")
default:
log.Println("defaults......")

}

}
35 changes: 35 additions & 0 deletions week3-channeel/channel_timeout.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import (
"fmt"
"time"
)

func main() {
ch1 := make(chan string)
go func() {
time.Sleep(4 * time.Second)
ch1 <- "ch1 is ready!"
}()

select {
case mess := <-ch1:
fmt.Println(mess)
case t := <- time.After(2 * time.Second):
fmt.Println("ch1 timeout ", t)

}

ch2 := make(chan string)
go func() {
time.Sleep(4 * time.Second)
ch2 <- "ch2 is ready !"
}()
select {
case mess := <- ch2:
fmt.Println(mess)
case t := <-time.After(5 * time.Second):
fmt.Println("ch2 is timeout", t)
}

}
20 changes: 20 additions & 0 deletions week3-channeel/channel_w_data.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package main

import (
"log"
"time"
)

func main() {
c := make(chan int)
go writeChan(c, 666)
time.Sleep(2 * time.Second)

}

func writeChan(c chan int, x int) {
log.Println(x)
c <- x
close(c)
log.Println(x)
}

0 comments on commit c5cd98c

Please sign in to comment.