如何限制对单个实时资源的并发访问
How to limit concurrent access to a single real-time resource
我正在尝试识别或理解适用于我遇到的特定并发编程问题的技术、惯用语。
为简单起见,假设我有一个实时图形用户界面 (UI),它始终以 10Hz 的频率在屏幕上重绘。
只要一组不同线程的至少一个实例 运行,我想在此 UI 上显示 "Busy" 指示器,并且我希望该指示器停止显示当这些线程中恰好有 0 个是 运行。只要 UI 启动,这些线程就可以随时启动和停止。
我目前正在 golang 中实现此功能(相关代码段在下方)。但总的来说,我是这样解决这个问题的:
通过互斥 waitLock
.[=25= 保护对计数器 int waitCount
(请求我们指示的线程数 "Busy")的 R+W 访问]
函数drawStatus()
:重绘整个UI(每100ms发生一次):
- 获取互斥锁
waitLock
- 如果整数
waitCount
> 0:
- 绘制 "Busy" 指标
- 释放互斥
waitLock
功能startWait()
:当一个线程需要指示繁忙时:
- 获取互斥锁
waitLock
- 增量整数
waitCount
- 释放互斥
waitLock
功能stopWait()
:当一个线程不再需要指示忙时:
- 获取互斥锁
waitLock
- 减 int
waitCount
- 释放互斥
waitLock
对我来说,感觉我没有充分利用 golang 的并发功能并诉诸于我熟悉的互斥锁。但即便如此,此代码中仍存在一个错误,其中 "Busy" 指示器会过早地消失。
老实说,我并不是在寻找任何人来帮助识别该错误,而是试图传达我感兴趣的特定逻辑。是否有更惯用的 golang 方法来解决这个问题?或者是否有我应该研究的更通用的编程模式?我正在使用的这项技术有任何特定的名称吗?关于正确执行此操作的建议或指示会很棒。谢谢。
下面是一些实现上述逻辑的修改过的片段
var WaitCycle = [...]rune{'', '', '', '', '', '', '', ''}
// type Layout holds the high level components of the terminal user interface
type Layout struct {
//
// ... other fields hidden for example ...
//
waitLock sync.Mutex
waitIndex int // the current index of the "busy" rune cycle
waitCount int // the current number of tasks enforcing the "busy" state
}
// function show() starts drawing the user interface.
func (l *Layout) show() *ReturnCode {
// timer forcing a redraw @ 10Hz
go func(l *Layout) {
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for {
select {
case <-tick.C:
// forces the UI to redraw all changed screen regions
l.ui.QueueUpdateDraw(func() {})
}
}
}(l)
if err := l.ui.Run(); err != nil {
return rcTUIError.specf("show(): ui.Run(): %s", err)
}
return nil
}
// function drawStatus() draws the "Busy" indicator at a specific UI position
func (l *Layout) drawStatus(...) {
l.waitLock.Lock()
if l.waitCount > 0 {
l.waitIndex = (l.waitIndex + 1) % WaitCycleLength
waitRune := fmt.Sprintf(" %c ", WaitCycle[l.waitIndex])
drawToScreen(waitRune, x-1, y, width)
}
l.waitLock.Unlock()
}
// function startWait() safely fires off the "Busy" indicator on the status bar
// by resetting the current index of the status rune cycle and incrementing the
// number of goroutines requesting the "Busy" indicator.
func (l *Layout) startWait() {
l.waitLock.Lock()
if 0 == l.waitCount {
l.waitIndex = 0
}
l.waitCount++
l.waitLock.Unlock()
}
// function stopWait() safely hides the "Busy" indicator on the status bar by
// decrementing the number of goroutines requesting the "Busy" indicator.
func (l *Layout) stopWait() {
l.waitLock.Lock()
l.waitCount--
l.waitLock.Unlock()
}
由于您所做的只是锁定单个计数器,因此您可以简化并只使用 sync/atomic 包。启动 goroutine 时调用 AddInt32(&x, 1)
,结束时调用 AddInt32(&x, -1)
。从您的绘图 goroutine 调用 LoadInt32(&x)
。
它取决于用例(你可以选择你想要的,在你产生错误或性能损失之前没有人关心),通道将锁隐藏在里面并使编码更简单 有一点性能成本 - 所以我建议在一般用例中使用通道,除非你正在考虑更高的性能):
在以下情况下使用频道:
1 - 转让所有权
2 - 协调
在以下情况下使用原语:
3 - 性能关键
4 - 保护 struct
的内部状态
参考:page 33
由于您使用的是软实时 UI 协调 goroutines 的数量,并且 不是性能关键 代码,我建议使用通道,我简化了您的代码 在这个例子中:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
for i := 0; i < 100; i++ {
go job() // e.g.: run all jobs
}
busy := 0
time.Sleep(10 * time.Millisecond) // or make sure at least on goroutine started
// 10Hz:
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for {
select {
case n := <-ch:
busy += n
case <-tick.C:
// forces the UI to redraw all changed screen regions
fmt.Printf(" %d \r", busy)
if busy == 0 {
return
}
}
}
}
func job() {
ch <- +1
time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
ch <- -1
}
var ch = make(chan int, 1)
我正在尝试识别或理解适用于我遇到的特定并发编程问题的技术、惯用语。
为简单起见,假设我有一个实时图形用户界面 (UI),它始终以 10Hz 的频率在屏幕上重绘。
只要一组不同线程的至少一个实例 运行,我想在此 UI 上显示 "Busy" 指示器,并且我希望该指示器停止显示当这些线程中恰好有 0 个是 运行。只要 UI 启动,这些线程就可以随时启动和停止。
我目前正在 golang 中实现此功能(相关代码段在下方)。但总的来说,我是这样解决这个问题的:
通过互斥
waitLock
.[=25= 保护对计数器 intwaitCount
(请求我们指示的线程数 "Busy")的 R+W 访问]函数
drawStatus()
:重绘整个UI(每100ms发生一次):- 获取互斥锁
waitLock
- 如果整数
waitCount
> 0:- 绘制 "Busy" 指标
- 释放互斥
waitLock
- 获取互斥锁
功能
startWait()
:当一个线程需要指示繁忙时:- 获取互斥锁
waitLock
- 增量整数
waitCount
- 释放互斥
waitLock
- 获取互斥锁
功能
stopWait()
:当一个线程不再需要指示忙时:- 获取互斥锁
waitLock
- 减 int
waitCount
- 释放互斥
waitLock
- 获取互斥锁
对我来说,感觉我没有充分利用 golang 的并发功能并诉诸于我熟悉的互斥锁。但即便如此,此代码中仍存在一个错误,其中 "Busy" 指示器会过早地消失。
老实说,我并不是在寻找任何人来帮助识别该错误,而是试图传达我感兴趣的特定逻辑。是否有更惯用的 golang 方法来解决这个问题?或者是否有我应该研究的更通用的编程模式?我正在使用的这项技术有任何特定的名称吗?关于正确执行此操作的建议或指示会很棒。谢谢。
下面是一些实现上述逻辑的修改过的片段
var WaitCycle = [...]rune{'', '', '', '', '', '', '', ''}
// type Layout holds the high level components of the terminal user interface
type Layout struct {
//
// ... other fields hidden for example ...
//
waitLock sync.Mutex
waitIndex int // the current index of the "busy" rune cycle
waitCount int // the current number of tasks enforcing the "busy" state
}
// function show() starts drawing the user interface.
func (l *Layout) show() *ReturnCode {
// timer forcing a redraw @ 10Hz
go func(l *Layout) {
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for {
select {
case <-tick.C:
// forces the UI to redraw all changed screen regions
l.ui.QueueUpdateDraw(func() {})
}
}
}(l)
if err := l.ui.Run(); err != nil {
return rcTUIError.specf("show(): ui.Run(): %s", err)
}
return nil
}
// function drawStatus() draws the "Busy" indicator at a specific UI position
func (l *Layout) drawStatus(...) {
l.waitLock.Lock()
if l.waitCount > 0 {
l.waitIndex = (l.waitIndex + 1) % WaitCycleLength
waitRune := fmt.Sprintf(" %c ", WaitCycle[l.waitIndex])
drawToScreen(waitRune, x-1, y, width)
}
l.waitLock.Unlock()
}
// function startWait() safely fires off the "Busy" indicator on the status bar
// by resetting the current index of the status rune cycle and incrementing the
// number of goroutines requesting the "Busy" indicator.
func (l *Layout) startWait() {
l.waitLock.Lock()
if 0 == l.waitCount {
l.waitIndex = 0
}
l.waitCount++
l.waitLock.Unlock()
}
// function stopWait() safely hides the "Busy" indicator on the status bar by
// decrementing the number of goroutines requesting the "Busy" indicator.
func (l *Layout) stopWait() {
l.waitLock.Lock()
l.waitCount--
l.waitLock.Unlock()
}
由于您所做的只是锁定单个计数器,因此您可以简化并只使用 sync/atomic 包。启动 goroutine 时调用 AddInt32(&x, 1)
,结束时调用 AddInt32(&x, -1)
。从您的绘图 goroutine 调用 LoadInt32(&x)
。
它取决于用例(你可以选择你想要的,在你产生错误或性能损失之前没有人关心),通道将锁隐藏在里面并使编码更简单 有一点性能成本 - 所以我建议在一般用例中使用通道,除非你正在考虑更高的性能):
在以下情况下使用频道:
1 - 转让所有权
2 - 协调
在以下情况下使用原语:
3 - 性能关键
4 - 保护 struct
的内部状态
参考:page 33
由于您使用的是软实时 UI 协调 goroutines 的数量,并且 不是性能关键 代码,我建议使用通道,我简化了您的代码 在这个例子中:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
for i := 0; i < 100; i++ {
go job() // e.g.: run all jobs
}
busy := 0
time.Sleep(10 * time.Millisecond) // or make sure at least on goroutine started
// 10Hz:
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for {
select {
case n := <-ch:
busy += n
case <-tick.C:
// forces the UI to redraw all changed screen regions
fmt.Printf(" %d \r", busy)
if busy == 0 {
return
}
}
}
}
func job() {
ch <- +1
time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
ch <- -1
}
var ch = make(chan int, 1)