除了通道之外,goroutine 之间还有其他的通信方式吗?

huangapple go评论64阅读模式
英文:

Is there any other way that goroutines can communicate with eachother, Other than channels?

问题

今天我接受了一次面试,其中一个面试官问了一个有趣的问题:我们知道通道是用于协程之间通信的媒介。但是,如果没有通道,或者不想使用通道,是否有其他替代的方法可以在Go语言中发送和读取协程之间的消息呢?

如果有的话,是怎样的呢?

英文:

I had been interview today and one of the interesting that i come across from the interviewer is we know that Channels are the medium through which goroutines can communicate with each other.

But, What if they is no channels..! or do not want to use channels, Is there any other alternative way that we can send and read messages to goroutines in golang?

If yes, How is it so?

答案1

得分: 3

通道并不是并发或并行实体之间的第一个也不是唯一的通信工具。还有许多其他的工具。

举个讽刺的例子,一个 goroutine 可以将消息保存到 Amazon S3 中的文件中,另一个 goroutine 可以获取该文件。这就是一种通信方式。

更高效的方式是创建并将消息写入本地文件,然后另一个 goroutine 可以读取该文件。

另一种方式是一个 goroutine 打开一个服务器套接字,另一个 goroutine 连接到该套接字。这样就形成了一个全双工的“通道”。

更简单和更高效的解决方案是通过共享变量发送消息,但是访问共享变量必须经过同步,可以使用 syncsync/atomic 包中的同步原语来实现。

两个 goroutine 可以共享一个切片(存储消息),当第一个 goroutine 想要向另一个 goroutine 发送消息时,它可以获取一个写锁(sync.RWMutex),将消息追加到切片中,然后释放锁。第二个 goroutine 可以使用读锁来检查切片是否有消息(长度大于 0),然后使用写锁从切片中取出一条消息(并删除它)。

英文:

Channel is not the first nor the only communication tool between concurrent or parallel entities. There are numerous others.

As a sarcastic example, one goroutine may upload a file holding the message to Amazon S3, and the other goroutine can fetch that file. This is a communication.

A more efficient one would be to create and write the message to a local file which the other goroutine can read.

Another could be opening a server socket by one goroutine, and connecting to that socket from the other goroutine. And you have a full duplex "channel".

To stay on the "Earth", much simpler and more efficient solutions would be to send messages via a shared variable, but access to it must be synchronized of course via synchronization primitives such as those in the sync and sync/atomic packages.

A slice (of messages) may be shared by the 2 goroutines, and when the first goroutine wants to send a message to the other, it may acquire a write lock (sync.RWMutex), append the message to the slice then release the lock. The second goroutine may use a read lock to check if the slice has messages (length > 0), then use a write lock to take a message from the slice (and delete it).

huangapple
  • 本文由 发表于 2022年6月16日 14:00:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/72641169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定