Package Mainimport ("FMT" "Sync" " Time") Type Userstruct{NamestringLocker*sync. Mutex}func (U*user) SetName (Wati *sync. Waitgroup, Namestring{defer func () {fmt. Println ("Unlock set Name:", name) U.locker.unlock () Wati. Done ()} () U.locker.lock () fmt. Println ("Lock set Name:", name) time. Sleep (1*Time . Second) U.name=name}func (U*user) GetName (Wati *sync. Waitgroup) {defer func () {fmt. Println ("Unlock Get Name:", U.name) U.locker.unlock () Wati. Done ()} () U.locker.lock () fmt. Println ("Lock Get Name:", U.name) time. Sleep (1*Time . Second)}func Main () {User:=user{} User. Locker=New(sync. Mutex) Wait:= &sync. waitgroup{} names:= []string{"a","b","C"} for_, Name: =range Names {wait. ADD (2) go user. SetName (wait, name) go user. GetName (Wait)} wait. Wait ()}
Transferred from: http://www.liguosong.com/2014/05/07/golang-sync-mutex/
Golang sync. Mutexes (2)