goroutine超时处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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")
}
}

无阻塞

1
2
3
4
5
6
7
8
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
default:
fmt.Println("abc")
}

通道关闭

  1. close(channel) 关闭通道
  2. j,more := <- channel 如果已关闭,则more为 false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
}

管道遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
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 只写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
}

控制并发数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main

import (
"fmt"
"sync"
"time"
)

var wg = sync.WaitGroup{}

func main(){
choice1()
choice2()

}

func choice1() {
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()
}

func choice2() {
ch := make(chan int ,2)
for i := 0; i < 100; i ++ {
go func(ch chan int){
defer wg.Done()
wg.Add(1)
ch <- 1
time.Sleep( time.Second)
fmt.Println(i)
<- ch
}(ch)
}
wg.Wait()
}