multithreading - 如何限制对单个实时资源的并发访问

标签 multithreading go concurrency real-time

我正在尝试识别或理解适用于我遇到的特定并发编程问题的技术、惯用语。

为简单起见,假设我有一个实时图形用户界面 (UI),它始终以 10Hz 的频率在屏幕上重绘。

每当一组不同线程的至少一个实例正在运行时,我想在此 UI 上显示一个“忙碌”指示器,并且我希望该指示器在恰好有 0 个线程正在运行时停止显示。只要 UI 启动,这些线程就可以随时启动和停止。

我目前正在 golang 中实现此功能(相关代码段在下方)。但总的来说,我按如下方式解决这个问题:

  • 通过互斥锁 waitLock 保护对计数器 int waitCount(请求我们指示“繁忙”的线程数)的 R+W 访问。

  • 函数 drawStatus():重绘整个 UI(每 100 毫秒发生一次):

    1. 获取互斥锁waitLock
    2. 如果 int waitCount > 0:
      1. 绘制“忙碌”指示符
    3. 释放互斥锁waitLock
  • 函数startWait():当一个线程需要指示繁忙时:

    1. 获取互斥锁waitLock
    2. 增加 int waitCount
    3. 释放互斥锁waitLock
  • 函数stopWait():当线程不再需要指示忙时:

    1. 获取互斥锁waitLock
    2. 递减 int waitCount
    3. 释放互斥锁waitLock

对我来说,感觉我没有充分利用 golang 的并发功能并诉诸于我熟悉的互斥体。但即便如此,此代码中仍存在一个错误,其中“忙碌”指示器会过早消失。

老实说,我并不是在寻找任何人来帮助识别该错误,而是试图传达我感兴趣的特定逻辑。是否有更惯用的 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)

关于multithreading - 如何限制对单个实时资源的并发访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53718146/

相关文章:

当 parent 离开僵尸时,Python subprocess.communicate 挂起

c# - 简单地分配变量时是否需要使用锁?

将字符串作为 %09d 的参数时,sprintf 的 golang 错误

go - websocket.Upgrader 到底是什么?

java - ConcurrentHashMap JDK1.7 中的“scanAndLockForPut”

c++ - 并发:C++11 内存模型中的原子性和 volatile

sql-server - 在更新语句中获取最新的行版本/时间戳值 - Sql Server

java - jdbc 驱动程序注销后停止/中断线程

java - 如何在 run 方法之外发送对象?

json - 如何通过 json 将键值对数组传递给结构的 golang slice