Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go锁定在结构的一个切片中_Go_Parallel Processing_Goroutine_Locks - Fatal编程技术网

Go锁定在结构的一个切片中

Go锁定在结构的一个切片中,go,parallel-processing,goroutine,locks,Go,Parallel Processing,Goroutine,Locks,我是新来的。我特别尝试使用锁(我不想使用通道)并行地向数组添加值。但不知何故,我的答案并不正确。我尝试了两种方法。将指针传递给切片并传递切片本身。我不是在寻找全局锁变量 方法1传递指针 type locks_block struct { population int mux sync.Mutex } func incr(ar *[] locks_block){ for i:=0;i<len(*ar);i++ { (*ar)[i].mux.Loc

我是新来的。我特别尝试使用锁(我不想使用通道)并行地向数组添加值。但不知何故,我的答案并不正确。我尝试了两种方法。将指针传递给切片并传递切片本身。我不是在寻找全局锁变量

方法1传递指针

type locks_block struct {
    population int
    mux sync.Mutex
}

func incr(ar *[] locks_block){

    for i:=0;i<len(*ar);i++ {

        (*ar)[i].mux.Lock()
        (*ar)[i].population = (*ar)[i].population+1;
        (*ar)[i].mux.Unlock()

    }
}

func main() {

    arr := make([]locks_block,5);

    go incr(&arr);
    go incr(&arr);
    go incr(&arr);
    go incr(&arr);


    fmt.Println(arr);
}
方法2通过切片

type locks_block struct {
    population int
    mux sync.Mutex
}

func incr(ar [] locks_block){

    for i:=0;i<len(ar);i++ {

        ar[i].mux.Lock()
        ar[i].population = ar[i].population+1;
        ar[i].mux.Unlock()

    }
}

func main() {

    arr := make([]locks_block,5);

    go incr(arr);
    go incr(arr);
    go incr(arr);
    go incr(arr);


    fmt.Println(arr);
}

无论哪种情况,输出都不正确。

您似乎正确使用了锁,但没有在打印arr之前等待goroutines完成。请尝试添加一个小的Do not use sync.Mutex,但添加指向它的指针。禁止复制sync.Mutex。但是切片不是已经通过引用传递了吗?Go没有任何通过引用传递的内容。对你来说:这太危险了。像其他人一样做。那么你是说示例1更好吗?不。我说locks_块应该包含一个*sync.Mutex。
package main

import (
    "fmt"
    "sync"
    "time"
)

type locks_block struct {
    population int
    mux        sync.Mutex
}

func incr(id int, ar []locks_block) {
    for i := 0; i < len(ar); i++ {
        ar[i].mux.Lock()
        ar[i].population = ar[i].population + 1
        fmt.Printf("goroutine #%v, population   %v\n", id, ar[i].population)
        ar[i].mux.Unlock()
    }
}

func main() {
    arr := make([]locks_block, 5)
    go incr(1, arr)
    go incr(2, arr)
    go incr(3, arr)
    go incr(4, arr)

    // this should give the goroutines enough time
    <-time.After(time.Millisecond * 500)
    fmt.Println(arr)
}