Golang sync.Mutex blocking problem

package main

import (

)
"sync"

)

type data struct {

sync.Mutex

}
func (d data) test (s string) {

d.Lock()
defer d.Unlock()
for i:=0;i<5 ;iPP  {
    println(s,i)
    //time.Sleep(time.Second)
}

}
func test_lock () {

var wg sync.WaitGroup
wg.Add(3)
var d data
go func() {
    defer wg.Done()
    d.test("write")
}()
go func() {
    defer wg.Done()
    d.test("read")
}()
go func() {
    defer wg.Done()
    d.test("new")
}()
wg.Wait()

}
func main () {

test_lock()

}

clipboard.png
d.lock is blocked. Shouldn"t you print anything else after all the write has been typed? Why can new get a lock after write prints part of it

May.22,2021

func (d data) test (s string) {

d.Lock ()
defer d.Unlock ()
for iPartio < 5; iPP {

println(s,i)
//time.Sleep(time.Second)

}
}
pointer problem, (d data) is equivalent to copying multiple locks to the, (d * data), then it becomes a lock, and there is no problem


func (d *data) test(s string) {

    d.Lock()
    defer d.Unlock()
    for i := 0; i < 5; iPP {
        println(s, i)
        //time.Sleep(time.Second)
    }
}

function (d data) test () you are wearing a value like this, so you get a copy

Menu