带有 for 循环的 golang 通道行为
golang channel behaviour with for loops
我很好奇通道的行为以及它们与循环相关的工作方式。假设我有以下代码:
消费者
tick := time.Tick(time.Duration(2) * time.Second)
for {
select {
case <-tick:
p.channel <-true
}
}
我有一个 goroutine 具有以下内容:
处理器
for {
select {
case canProcess := <-p.channel:
// synchronous process that takes longer than 2 seconds
case <-p.stop:
return
}
}
当 Consumer 推送到通道的速度比 Processor 完成其同步过程的速度快时会发生什么?
他们是堆积起来等待 处理器 完成,还是直接跳过 "beat"?
如果它们堆积起来,是否存在内存泄漏的可能性?
我知道我可以将同步过程放在 goroutine 中,但这确实是为了了解通道的行为方式。 (即我的例子有一个 2 秒的滴答声,但它不是必须的)。
select 只会调用下一个 time.Tick 如果前面的案例对应的代码已经完成,
你仍然可以通过指定通道的大小来获得一些杠杆,即 channel := make(chan bool,10)
见下文:
func main() {
channel := make(chan bool, 10)
go func() {
tick := time.Tick(time.Duration(1) * time.Second)
for {
select {
case <-tick:
fmt.Printf("Producer: TICK %v\n", time.Now())
channel <- true
}
}
}()
for {
select {
case canProcess := <-channel:
time.Sleep(3* time.Second)
fmt.Printf("Consumer: Completed : %v\n")
fmt.Printf("%v\n", canProcess)
}
}
}
我很好奇通道的行为以及它们与循环相关的工作方式。假设我有以下代码:
消费者
tick := time.Tick(time.Duration(2) * time.Second)
for {
select {
case <-tick:
p.channel <-true
}
}
我有一个 goroutine 具有以下内容:
处理器
for {
select {
case canProcess := <-p.channel:
// synchronous process that takes longer than 2 seconds
case <-p.stop:
return
}
}
当 Consumer 推送到通道的速度比 Processor 完成其同步过程的速度快时会发生什么?
他们是堆积起来等待 处理器 完成,还是直接跳过 "beat"?
如果它们堆积起来,是否存在内存泄漏的可能性?
我知道我可以将同步过程放在 goroutine 中,但这确实是为了了解通道的行为方式。 (即我的例子有一个 2 秒的滴答声,但它不是必须的)。
select 只会调用下一个 time.Tick 如果前面的案例对应的代码已经完成,
你仍然可以通过指定通道的大小来获得一些杠杆,即 channel := make(chan bool,10)
见下文:
func main() {
channel := make(chan bool, 10)
go func() {
tick := time.Tick(time.Duration(1) * time.Second)
for {
select {
case <-tick:
fmt.Printf("Producer: TICK %v\n", time.Now())
channel <- true
}
}
}()
for {
select {
case canProcess := <-channel:
time.Sleep(3* time.Second)
fmt.Printf("Consumer: Completed : %v\n")
fmt.Printf("%v\n", canProcess)
}
}
}