Golang阻塞的管道

Golang阻塞的管道

疑惑: 对于处理不完任务的管道,剩下的任务是不是按照顺序处理的?

测试思路

  1. 生产者每 3 毫秒生产一条
  2. 消费者每秒消费一条
  3. 观察数据打印

如果数据是递增的,就是队列

不是递增的,那就是内部实现的是锁的竞争

代码

package main

import (
	"log"
	"time"
)

var Queue chan int // 任务管道
var Token int // 数据源,数据递增

// 任务每秒消费一条
func work(data int)  {
	log.Println(data)
	time.Sleep(time.Second)
}

// 数据0.3秒生产一条
func producer()  {
	ticker := time.NewTicker(time.Millisecond * 300)
	for {
		<-ticker.C
		go func() {
			Token++
			Queue <-Token
		}()
	}
}

func main() {
	Queue = make(chan int, 5)

	go producer()

	for {
		data := <- Queue
		work(data)
	}
}

测试结果1

2021/07/19 22:40:03 1
2021/07/19 22:40:04 2
2021/07/19 22:40:05 3
2021/07/19 22:40:06 4
2021/07/19 22:40:07 5
2021/07/19 22:40:08 6
2021/07/19 22:40:09 7
2021/07/19 22:40:10 8
2021/07/19 22:40:11 11
2021/07/19 22:40:12 14
2021/07/19 22:40:13 17
2021/07/19 22:40:14 21
2021/07/19 22:40:15 24
2021/07/19 22:40:16 27
2021/07/19 22:40:17 31
2021/07/19 22:40:18 34
2021/07/19 22:40:19 38
2021/07/19 22:40:20 41

测试结果2

2021/07/19 22:41:10 1
2021/07/19 22:41:11 2
2021/07/19 22:41:12 3
2021/07/19 22:41:13 4
2021/07/19 22:41:14 5
2021/07/19 22:41:15 6
2021/07/19 22:41:16 7
2021/07/19 22:41:17 8
2021/07/19 22:41:18 11
2021/07/19 22:41:19 14
2021/07/19 22:41:20 17
2021/07/19 22:41:21 21
2021/07/19 22:41:22 24
2021/07/19 22:41:23 27

结论

不是按序到达的

posted @ 2021-07-19 22:47  maob  阅读(288)  评论(0编辑  收藏  举报