内容纲要

[go]
package main

import (
"fmt"
"time"
)

func writeChannel(c chan<- int, x int) {
fmt.Println(x)
c <- x
close(c)
fmt.Println(x)
}

func main() {
c := make(chan int)
go writeChannel(c, 10)
time.Sleep(2 * time.Second)
fmt.Println("Read:", <-c)
time.Sleep(2 * time.Second)

_, ok := <-c
if ok {
fmt.Println("Channel is open!")
} else {
fmt.Println("Channel is closed!")
}
}

[/go]

[code]
10
Read: 10
10
Channel is closed!
[/code]

[go]
package main

import (
"fmt"
)

func main() {
numbers := make(chan int, 5)

counter := 10
for i := 0; i < counter; i++ {
select {
case numbers <- i:
default:
fmt.Println("Not enough space for", i)
}
}

for i := 0; i < counter*2; i++ {
select {
case num := <-numbers:
fmt.Println(num)
default:
break
}
}
}

[/go]

[code]
Not enough space for 5
Not enough space for 6
Not enough space for 7
Not enough space for 8
Not enough space for 9
0
1
2
3
4
[/code]

发表评论

电子邮件地址不会被公开。 必填项已用*标注