最大元素-致命错误:所有goroutine都处于睡眠状态-死锁

时间:2020-04-07 12:34:37

标签: multithreading go synchronization deadlock goroutine

在我的机器上$(document).ready(function(){ $('#swmodel').on('show.bs.modal', function (event) { var Id = button.data('id'); var time = button.data('time'); document.getElementById('recipient-name').value = Id; document.getElementById('time-name').value = time; }); }); 是4

下面的代码:

runtime.NUMCPU

package main

import (
    "fmt"
    "sync"

    "github.com/myhub/a/expressions"
)

var list = make([]int, 1e5)

func main() {

    value := 0
    for i := 0; i < 1e5; i++ {
        list[i] = value // sample list
        value = value + 1
    }
    var wg sync.WaitGroup
    wg.Add(1)
    var max1 int
    go func() {
        max1 = expressions.Max(list[0 : 1e5/4-1])
    }()
    wg.Add(1)
    var max2 int
    go func() {
        max2 = expressions.Max(list[1e5/4 : 1e5/2-1])
    }()
    wg.Add(1)
    var max3 int
    go func() {
        max3 = expressions.Max(list[1e5/2 : 3*1e5/4-1])
    }()
    wg.Add(1)
    var max4 int
    go func() {
        max4 = expressions.Max(list[3*1e5/4 : 1e5-1])
    }()

    wg.Wait()
    fmt.Println(max1, max2, max3, max4)

}

给出错误:

package expressions

func Max(list []int) int {

    length := len(list)
    if length > 1 {

        if list[0] > list[length-1] {

            return Max(list[:length-1])
        } else {

            return Max(list[1:length])
        }
    }
    return list[0]
}

对于具有未排序数据的长度fatal error: all goroutines are asleep - deadlock! goroutine 1 [semacquire]: sync.runtime_Semacquire(0xc00001a0a8) /usr/local/go/src/runtime/sema.go:56 +0x42 sync.(*WaitGroup).Wait(0xc00001a0a0) /usr/local/go/src/sync/waitgroup.go:130 +0x64 main.main() /home/machine1/code/src/github.com/myhub/a/Main.go:41 +0x1b5 exit status 2 的列表,

如何在四个操作系统线程之间分配make([]int, 1e5)的负载?找到最大元素

1 个答案:

答案 0 :(得分:2)

您需要在gorutines中调用wg.Done() 例如:

wg.Add(1)
var max4 int
go func() {
    max4 = expressions.Max(list[3*1e5/4 : 1e5-1])
    wg.Done()
}()