问题描述
下面是如何使用互斥锁来安全访问数据的示例.我将如何使用CSP(通信顺序过程)进行相同的操作使用互斥锁和解锁?
Below is an example of how to use mutex lock in order to safely access data. How would I go about doing the same with the use of CSP (communication sequential processes) instead of using mutex lock’s and unlock’s?
type Stack struct {
top *Element
size int
sync.Mutex
}
func (ss *Stack) Len() int {
ss.Lock()
size := ss.size
ss.Unlock()
return size
}
func (ss *Stack) Push(value interface{}) {
ss.Lock()
ss.top = &Element{value, ss.top}
ss.size++
ss.Unlock()
}
func (ss *SafeStack) Pop() (value interface{}) {
ss.Lock()
size := ss.size
ss.Unlock()
if size > 0 {
ss.Lock()
value, ss.top = ss.top.value, ss.top.next
ss.size--
ss.Unlock()
return
}
return nil
}
推荐答案
如果您实际上要查看Go如何实现通道,则实际上您会在数组周围看到一个互斥体,并带有一些其他线程处理来阻止执行直到该值通过.通道的工作是轻松地将数据从内存中的一个位置移动到另一个位置.因此,在有锁和开锁的地方,会有类似以下示例的内容:
If you actually were to look at how Go implements channels, you'd essentially see a mutex around an array with some additional thread handling to block execution until the value is passed through. A channel's job is to move data from one spot in memory to another with ease. Therefore where you have locks and unlocks, you'd have things like this example:
func example() {
resChan := make(int chan)
go func(){
resChan <- 1
}()
go func(){
res := <-resChan
}
}
因此,在该示例中,第一个goroutine在发送值之后被阻塞,直到第二个goroutine从通道读取.
So in the example, the first goroutine is blocked after sending the value until the second goroutine reads from the channel.
要在使用互斥锁的Go中执行此操作,可以使用sync.WaitGroup,它将在设置值时向组中添加一个,然后将其从组中释放,第二个goroutine将锁定然后解锁该值.
To do this in Go with mutexes, one would use sync.WaitGroup which will add one to the group on setting the value, then release it from the group and the second goroutine will lock and then unlock the value.
在您的示例中,奇数是1没有goroutine,因此所有这些都发生在单个主goroutine中,并且更传统地使用了锁(例如在c线程中),因此通道实际上不会完成任何事情.您所看到的示例将被视为反模式,例如golang谚语说:不要通过共享内存进行通信,而应该通过通信来共享内存."
The oddities in your example are 1 no goroutines, so it's all happening in a single main goroutine and the locks are being used more traditionally (as in c thread like) so channels won't really accomplish anything. The example you have would be considered an anti-pattern, like the golang proverb says "Don't communicate by sharing memory, share memory by communicating."
这篇关于如何在Go中使用通道安全地同步数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!