【发布时间】:2018-11-25 04:15:04
【问题描述】:
有一个不重要结构Message的队列,有经典的push和pop方法:
type Queue struct {
messages list.List
}
//The implementation is not relevant for the sake of the question
func (q *Queue) Push(msg Message) { /*...*/ }
func (q *Queue) Pop() (Message, bool) { /*...*/ }
/*
* NewTimedChannel runs a goroutine which pops a message from the queue every
* given time duration and sends it over the returned channel
*/
func (q *Queue) NewTimedChannel(t time.Duration) (<-chan Message) {/*...*/}
Push 函数的客户端将是一个 web gui,用户将在其中发布他们的消息。NewTimedChannel 返回的通道的客户端将是一个服务,它通过网络将每条消息发送到不相关的端点。
我是并发新手,我有以下问题:
我知道,由于Queue.messages 是在用户提交 Web 表单后处理推送消息的主 goroutine 和为每个 NewTimedChannel 调用创建的 goroutine 之间的共享状态,我需要锁定它。
我是否需要在所有 Push、Pop 和 NewTimedChannel 方法中使用 sync.Mutex 锁定和解锁?
还有更惯用的方法来处理这个特定问题在 go 环境中?
【问题讨论】:
-
1.是的。可以看出,如果在比赛检测器下运行(你应该习惯这样做)。 2.没有。
标签: go concurrency locking