Does golang automatically add locks to ensure concurrency security?

The version of

golang is 1.9.2

recently contacted with the concurrent locking function of golang, I did a multi-goroutine counting exercise according to the example, and found that the results of locking and unlocking are the same. Is this because of the machine? (at least on my computer and on https://play.golang.org/) or does version 1.9 of go no longer use mutex lock data? If it"s my test method, how can I test the difference between locked and unlocked in the right way?

the code is as follows:

package main

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

type SafeCounter struct {
    v  map[string]int
    mux sync.Mutex
}

func (c *SafeCounter) Inc(key string) {

    c.mux.Lock()

    c.v[key]PP

    c.mux.Unlock()
}

func (c *SafeCounter) Value(key string) int {

    defer c.mux.Unlock()

    c.mux.Lock()

    return c.v[key]
}

func main() {
    c := SafeCounter{
        v: make(map[string]int),
    }

    for i := 0; i < 1000; iPP {
        go c.Inc("somekey")
    }

    time.Sleep(time.Second)

    fmt.Println(c.Value("somekey"))
}

output 1000
remove all locks, or 1000

Mar.05,2021

Don't take any chances. The map will definitely collapse if it is not locked. When you get online, the program exits abnormally. There is no problem with your example. There may be panic, only after a few more trips. You try to use go run-race main.go, to check whether there is any data competition.


  • Native map is not thread safe. Starting with go1.6 , runtime will detect concurrent read and write map, and will trigger crash if concurrent read and write map is detected.
  • sync.Map is thread safe.

No, and go does not guarantee that all goroutine is executed by Synchronize, and statements are reordered (the order of execution detected by one goroutine may be different from that detected by another goroutine)

use sync and sync/atomic packages to ensure thread Synchronize and thread safety

http://docscn.studygolang.com.
https://golang.org/ref/mem


obviously not, although most places using golang involve concurrency security processing, so I encapsulate a lot of concurrency security packages and types in my project: http://gf.johng.cn/494392

.

by the way, golang's atomic atomic operation is the most efficient of all locking mechanisms, so where atomic operations can be used, use atomic operations as much as possible. Most of the underlying packages I implement gtype are also based on atomic.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b39678-4d82c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b39678-4d82c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?