对于那些对Go中并发的人来说。
我创建了一个小型有趣的程序,以了解与直观示例的同时发生。
步骤: -
-
创建一个缓冲通道,以在其他两个GO例程中使用频道中的最低值
ch:= make(chan int,2) -
创建两个GO例程,该例程将消耗我们在步骤1中创建的频道的数据
Go iacceptonlynegativeFolks(CH)
Go iacceptonlypositionFolks(CH) -
将初始信号/数据发送到通道
ch <-1 -
保持一些睡眠 /使用SELECT CASE /其他一些策略,以阻止Main退出。
Time.Sleep(Time.MilliseCond*5)
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int, 2)
// initiate +ve & -ve folks
go iAcceptOnlyNegativeFolks(ch)
go iAcceptOnlyPositiveFolks(ch)
// ignite fire between +ve & -ve folks 😅
ch <- 1
// this is just simple way to block main else go routines will exit along with main
time.Sleep(time.Millisecond * 5)
}
func iAcceptOnlyPositiveFolks(ch chan int) {
for {
select {
case x := <-ch:
if x > 0 {
fmt.Println(x, " is a positive folk")
ch <- x + 1
} else {
// giving some motivation to -ve folk to become +ve folk
ch <- x * (-1)
}
}
}
}
func iAcceptOnlyNegativeFolks(ch chan int) {
for {
select {
case x := <-ch:
if x < 0 {
fmt.Println(x, " is a negative folk")
ch <- x - 1
} else {
// giving some motivation to +ve folk to become -ve folk
ch <- x * (-1)
}
}
}
}
sample output 1:-
-1 is a negative folk
-2 is a negative folk
-3 is a negative folk
4 is a positive folk
-5 is a negative folk
-6 is a negative folk
7 is a positive folk
-8 is a negative folk
9 is a positive folk
10 is a positive folk
11 is a positive folk
sample output 2:-
1 is a positive folk
2 is a positive folk
3 is a positive folk
-4 is a negative folk
-5 is a negative folk
6 is a positive folk
7 is a positive folk
说明: -
- 我们正在创建一个缓冲通道作为两个GO例程之间的通信媒介
- iacceptonlynegativeFolks&iacceptonlypositionFolks功能 将同时读取来自频道的数据(当时可以访问哪个例程,它将从渠道读取该数据)
- 在运行上述程序后,我们将对每个执行都有不同的规定,因为它同时运行,我们不知道哪个例程将在某个时间点访问频道数据。
请随时添加任何评论/建议/错误等
请关注媒介以获取有趣的事情