登录
首页 >  Golang >  Go问答

测试信号量实现时出错

来源:stackoverflow

时间:2024-04-17 12:03:36 322浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《测试信号量实现时出错》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我正在练习并发编程,并且我已经开始在 go 中实现几种模式和结构。我还添加了使用信号量作为互斥体的测试,以增加共享计数器。我的实现显然有问题,因为运行测试文件几次后,一些测试通过,而另一些则失败。 我的猜测是,不知何故,多个线程可以在没有阻塞的情况下传递 wait() 调用,并且可以并发访问计数器变量,但我不明白为什么。如有任何帮助,我们将不胜感激!

semaphore.go

package semaphore

import (
    "sync"
)

type semaphore struct {
    capacity int

    count int
    sync.mutex
    condition chan bool
}

func (s *semaphore) wait() {
    s.lock()
    defer s.unlock()

    if s.count == s.capacity {
        s.unlock()
        <-s.condition
        s.lock()
    }

    s.count++

}

func (s *semaphore) signal() {
    s.lock()
    defer s.unlock()

    select {
    case s.condition <- true:
    default:
    }

    s.count--

}

func newsemaphore(n int) *semaphore {
    return &semaphore{count: 0, capacity: n, condition: make(chan bool)}
}

semaphore_test.go

package semaphore

import (
    "sync"
    "testing"
)

func TestMutexSemaphore(t *testing.T) {

    s := NewSemaphore(1)
    wg := sync.WaitGroup{}
    sharedCounter := 0
    iters := 25
    n := 20

    testfun := func(mutex *Semaphore) {
        defer wg.Done()
        for j := 0; j < iters; j++ {
            s.Wait()
            sharedCounter++
            s.Signal()
        }

    }
    wg.Add(n)
    for i := 0; i < n; i++ {
        go testfun(s)
    }

    wg.Wait()
    if sharedCounter != iters*n {
        t.Errorf("Bad counter value:%d expected %d", sharedCounter, n*iters)
    }

}

解决方案


wait中,当您唤醒并锁定时,不能保证条件仍然成立。锁定后,您应该再次检查条件:

for s.count == s.capacity {
        s.Unlock()
        <-s.condition
        s.Lock()
    }

signal 中,你应该在叫醒其他人之前先 count--

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>