卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34474本站已运行393

如何解决死锁(等待失败测试的信号)

如何解决死锁(等待失败测试的信号)

php小编小新为您介绍如何解决死锁问题。死锁是并发编程中常见的问题,当两个或多个进程互相等待对方释放资源时,会出现死锁现象。为了解决这个问题,我们可以采用一些常见的方法,如使用互斥锁、避免资源竞争、使用超时机制等。通过合理的设计和调整,我们可以有效地避免死锁的发生,提高程序的并发性和稳定性。接下来,让我们一起深入了解如何解决死锁问题吧!

问题内容

我有两个 goroutine,它们是测试期间的两个 testxxx 函数。我使用条件变量来同步这些 goroutine。然而,一旦其中一个测试失败,而另一个正在等待信号。僵局来了。另外,如果 testfunctionb 失败,我希望 testfunctiona 也失败。

var cond sync.cond
func testfunctiona(t *testing.t){
   // ... some codes...
   cond.wait()
}
func testfunctionb(t *testing.t){
   // ... some codes...
   t.fail()
   // ... some codes...
   cond.broadcast()
}

我尝试过一些方法,例如:

var cond sync.Cond
var A_t *testing.T
func TestFunctionA(t *testing.T){
   // ... Some codes...
   A_t = t
   // ... Some codes...
   cond.Wait()
}
func TestFunctionB(t *testing.T){
   // ... Some codes...
   t.Cleanup(func(){
      if !A_t.Failed(){
          A_t.Fail()
      }
      cond.Broadcast()
   })
   t.Fail()
   // ... Some codes...
   cond.Broadcast()
}

但是当functionb没有错误时,a_t.fail()仍然会被触发。

我也在考虑使用 context.context()。但是,我不知道如何在上下文中运行测试函数。 感谢您阅读我的问题!我感谢任何评论或讨论!

解决方法

一个测试不应与另一个测试交互。但是,当使用子测试时,我们可以在测试用例之间共享任何内容。

这是一个示例:

package main

import (
    "errors"
    "testing"
)

func TestFruits(t *testing.T) {
    var err error
    t.Run("test apple", getTestAppleFunc(&err))
    t.Run("test banana", getTestBananaFunc(&err))
}

func handleError(t *testing.T, err *error) {
    if err != nil && *err != nil {
        t.Error(*err)
    }
}

func getTestAppleFunc(err *error) func(*testing.T) {
    return func(t *testing.T) {
        handleError(t, err)
        *err = errors.New("Apple failed")
    }
}

func getTestBananaFunc(err *error) func(*testing.T) {
    return func(t *testing.T) {
        handleError(t, err)
    }
}
  • 在函数 gettestbananafuncgettestapplefunc 中,错误指针作为参数传递。
  • 在上面的例子中,首先执行的是gettestapplefunc
  • 如果在 gettestapplefunc 中赋值错误(如上例所示),则 gettestbananafunc 函数将失败。
卓越飞翔博客
上一篇: 如何转储容器入口点进程的 goroutine?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏