即使使用互斥锁和延迟也会对运行goroutines感到恐慌

即使使用互斥锁和延迟也会对运行goroutines感到恐慌,go,mutex,goroutine,Go,Mutex,Goroutine,我尝试运行goroutines并应用互斥锁和延迟。然而,在运行goroutines时,我将面临恐慌。我有办法解决这个问题吗?我创建了一个队列和链表,其中包含一些用于显示、排队(添加)和出列(pop)的函数,并对其应用一些并发性。我知道wg.Add(n),n是您运行的goroutine的数量,您希望使用互斥锁来确保goroutine一次运行一个。在启动go例程之前使用wg.Add(1)。执行代码时没有互斥锁.Unlock() fatal error: all goroutines are asle

我尝试运行goroutines并应用互斥锁和延迟。然而,在运行goroutines时,我将面临恐慌。我有办法解决这个问题吗?我创建了一个队列和链表,其中包含一些用于显示、排队(添加)和出列(pop)的函数,并对其应用一些并发性。我知道
wg.Add(n)
,n是您运行的goroutine的数量,您希望使用互斥锁来确保goroutine一次运行一个。

在启动go例程之前使用
wg.Add(1)

执行代码时没有互斥锁.Unlock()

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [semacquire]:
sync.runtime_Semacquire(0x89ec50)
        c:/go/src/runtime/sema.go:56 +0x49
sync.(*WaitGroup).Wait(0x89ec48)
        c:/go/src/sync/waitgroup.go:130 +0x6b
main.main()
        C:/Projects/Go/src/xxx/main.go:145 +0xd85
exit status 2
您正在锁定但从未解锁:

if currentNode == nil {
    fmt.Println("There are no patients.")
    return nil
}
func(p*queue)displayallpatients()错误{
推迟工作组完成()

mutex.Lock()//您能否共享完整的代码以及导致死锁的输入序列?粗略地看一下代码,您将向等待组添加3个。因此,如果3个goroutine不执行wg.Done()然后您将看到死锁错误。@SaiRaviTejaK我刚刚在顶部添加了。因此,即使我将mutex.unlock()放在fmt.Println(“显示所有患者及其预约时间”)上,我也需要在前面提到的代码下面添加mutex unlock?``fmt.Println(currentNode.item,currentNode.time)表示currentNode.next!=nil{currentNode=currentNode.next fmt.Println(currentNode.item,currentNode.time)}mutex.Unlock()@xodmqjw@Smbsg,当您提前返回时(当currentNode==nil为true时),在解锁互斥锁时,您永远无法到达代码段,因为函数的执行已停止。因此,锁定后会出现死锁。您可以使用defer解锁(如我所述,将其添加到“if”分支之前),或者不要提前返回。因此,如果只有一个返回,我可以在返回之前执行互斥锁和互斥解锁?无论如何,感谢您的良好响应。是的,您可以像在函数showalldoctorsrecursive()中那样执行。例如,```func(p*linkedList)showalldoctorsrecursive()错误{defer wg.Done()mutex.lock(){if p.head!=nil{printRecursiveF(p.head)}else{fmt.Println(“列表为空”)}mutex.Unlock()返回nil}func printRecursiveF(n*Node2){mutex.Lock(){if n!=nil{printRecursiveF(n.next)fmt.Println(n.item,n.next.time)}mutex.Unlock()}“不过,我在这件事上陷入了僵局。这是因为我没有完成延期工作吗?”?
if currentNode == nil {
    fmt.Println("There are no patients.")
    return nil
}
func (p *queue) displayallpatients() error {
    defer wg.Done()
    mutex.Lock() // <- here we acquire a lock
    {
        currentNode := p.front
        if currentNode == nil {
            fmt.Println("There are no patients.")
            return nil // <- here we return without releasing the lock
        }
        // ...
    }
    mutex.Unlock() // <- never reach if currentNode == nil is true
    return nil
}
func (p *queue) displayallpatients() error {
    defer wg.Done()
    defer mutex.Unlock() // <- defers the execution until the func returns (will release the lock)
    mutex.Lock()
    {
        currentNode := p.front
        if currentNode == nil {
            fmt.Println("There are no patients.")
            return nil
        }
        // ...
    }
    
    return nil
}