Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Mutexes need initialization in Go?

Tags:

go

mutex

locking

I am writing some thread-safe thingy in Go. I try to use Mutexes.

The example I've found here, seems to use the Mutexes without any initialization:

...
// essential part of the referred page
// (it is not my code, I know the pointer is unneeded here,
// it is the code of the referred site in the link - @peterh)

var mutex = &sync.Mutex{}
var readOps uint64 = 0
var writeOps uint64 = 0

for r := 0; r < 100; r++ {
    go func() {
        total := 0
        for {
            key := rand.Intn(5)
            mutex.Lock()
....

I am a little bit surprised. Is it real, that they don't need any initialization?

like image 755
peterh Avatar asked Aug 17 '17 20:08

peterh


People also ask

Does a mutex need to be initialized?

A mutex must be initialized (either by calling pthread_mutex_init(), or statically) before it may be used in any other mutex functions.

How does mutex work in go?

A Mutex is used to provide a locking mechanism to ensure that only one Goroutine is running the critical section of code at any point in time to prevent race conditions from happening. Mutex is available in the sync package. There are two methods defined on Mutex namely Lock and Unlock.

What is sync mutex in Golang?

Golang has a mechanism called Mutex, or mutual exclusion, which allows us to write code shielded against race conditions. In Go, Mutex is implemented in the sync package, and has functions to lock and unlock processes. It usually works together with another type: WaitGroup, also implemented in the sync package.

What does sync mutex lock?

A sync. Mutex object represents a single mutually exclusive lock. Only one goroutine at a time will be able to obtain the lock. While a goroutine has the lock, all other goroutines attempting to obtain that same lock will be blocked until the mutex is unlocked by the goroutine that has the lock.


1 Answers

A mutex does not need initialization.

Also that could just be var mutex sync.Mutex, there's no need for a pointer, same for the int values, there's no need to set them to 0, so that example you found could be improved. In all these cases the zero value is fine.

See this bit of effective go:

https://golang.org/doc/effective_go.html#data

Since the memory returned by new is zeroed, it's helpful to arrange when designing your data structures that the zero value of each type can be used without further initialization. This means a user of the data structure can create one with new and get right to work. For example, the documentation for bytes.Buffer states that "the zero value for Buffer is an empty buffer ready to use." Similarly, sync.Mutex does not have an explicit constructor or Init method. Instead, the zero value for a sync.Mutex is defined to be an unlocked mutex.

like image 153
Kenny Grant Avatar answered Oct 15 '22 10:10

Kenny Grant