goroutine超时处理
package main
import (
"fmt"
"time"
)
func main() {
c1 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c1 <- "result 1"
}()
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout 1")
}
c2 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c2 <- "result 2"
}()
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
}
}
无阻塞
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
default:
fmt.Println("abc")
}
通道关闭
- close(channel) 关闭通道
- j,more := <- channel 如果已关闭,则more为 false
package main
import "fmt"
func main() {
jobs := make(chan int, 5)
done := make(chan bool)
go func() {
for {
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
}
}()
for j := 1; j <= 3; j++ {
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("sent all jobs")
<-done
}
管道遍历
package main
import "fmt"
func main() {
queue := make(chan string, 2)
queue <- "one"
queue <- "two"
close(queue)
for elem := range queue {
fmt.Println(elem)
}
}
只读和只写管道
<-chan string
只读chan<- string
只写
package main
import "fmt"
func test(jobs chan int, done chan bool) {
for {
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
}
}
func sendMsg(jobs chan int){
for j := 1; j <= 3; j++ {
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("sent all jobs")
}
func main() {
jobs := make(chan int, 5)
done := make(chan bool)
go test(jobs, done)
go sendMsg(jobs)
<-done
}
控制并发数
package main
import (
"fmt"
"sync"
"time"
)
var wg = sync.WaitGroup{}
func main(){
ch := make(chan int ,2)
for i := 0; i < 100; i ++ {
wg.Add(1)
ch <- 1
go func(ch chan int){
defer wg.Done()
time.Sleep( time.Second)
fmt.Println(i)
<- ch
}(ch)
}
wg.Wait()
}