On Thu, Nov 5, 2015 at 7:50 PM, Gyu-Ho Lee <
gyu...@gmail.com> wrote:
>
> Go documentation explains:
>
> type Mutex
>
> type Mutex struct {
> // contains filtered or unexported fields
> }
>
> A Mutex is a mutual exclusion lock. Mutexes can be created as part of other
> structures; the zero value for a Mutex is an unlocked mutex.
>
>
> But I cannot find any documentation about exact scope of sync.Mutex, and to
> what extent
> it locks and unlocks the data. What if I want to use mutex without struct?
> Or am I supposed
> to use it only with struct? Sometimes I want to have memory unsafe data
> structures(slice, map)
> locally and update it with concurrency without defining structs.
You are looking at this incorrectly in some way that I don't
understand. A sync.Mutex is a value with two methods: Lock and
Unlock. Lock acquires a lock on the mutex. Unlock releases it. Only
one goroutine can acquire the lock on the mutex at a time.
That's all there is. A mutex doesn't have a scope. It can be a field
of a struct but it doesn't have to be. A mutex doesn't protect
anything in particular by itself. You have to write your code to call
Lock, do the protected operations, and then call Unlock.
Your example code looks fine.
Ian