gpt4 book ai didi

multithreading - golang线程模型比较

转载 作者:IT王子 更新时间:2023-10-29 02:11:33 25 4
gpt4 key购买 nike

我有一条数据

type data struct {
// all good data here
...
}

此数据由管理器拥有,其他线程仅供读取使用。管理者需要定期更新数据。我如何为此设计线程模型?我可以想到两个选项:

1.

type manager struct {
// acquire read lock when other threads read the data.
// acquire write lock when manager wants to update.
lock sync.RWMutex
// a pointer holding a pointer to the data
p *data
}

2。

type manager struct {
// copy the pointer when other threads want to use the data.
// When manager updates, just change p to point to the new data.
p *data
}

第二种方法行得通吗?看来我不需要任何锁。如果其他线程得到一个指向旧数据的指针,那么manager更新一下原来的指针就好了。由于 Go 语言会进行 GC,在所有其他线程读取旧数据后,它会自动释放。我说得对吗?

最佳答案

您的第一个选择很好,而且可能是最简单的选择。但是,它可能会导致许多读取器性能不佳,因为它可能难以获得写锁。

正如对您的问题的评论所述,您的第二个选项(按原样)可能会导致竞争条件并导致不可预测的行为。

您可以使用 atomic.Value 实现第二个选项.这将允许您存储指向某些数据结构的指针并自动更新它以供下一个读者使用。例如:

// Data shared with readers
type data struct {
// all the fields
}

// Manager
type manager struct {
v atomic.Value
}

// Method used by readers to obtain a fresh copy of data to
// work with, e.g. inside loop
func (m *manager) Data() *data {
return m.v.Load().(*data)
}

// Internal method called to set new data for readers
func (m *manager) update() {
d:=&data{
// ... set values here
}
m.v.Store(d)
}

关于multithreading - golang线程模型比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45287348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com