Hi all.

 

I have a question about the mutexes provided by the sync library.  It is 
correct to say that using the 3 lines of code below, anywhere in Go code, won't 
have any effect, other than to introduce a slight, non-blocking delay while 
they execute?  In other words, the mutex is guaranteed to be the same before 
and after, and won’t hang your code, regardless of what else is going on, 
including in other GoRoutines.

 

       // Note: x is a sync.Mutex.

       if x.TryLock() {

              // x was unlocked but is now locked by us.

              x.Unlock()

       }

 

If so, then would these functions be non-blocking, correct, and safe to use?

 

// Note: x will always be unlocked upon return.

func TryUnlock(x *sync.Mutex) (success bool) {

       if x.TryLock() {

              // x was unlocked but is now locked by us.

              x.Unlock()

              return true

       }

       // x was unlocked to start with.

       return false

}

 

// Note: x will be the same (locked or unlocked) upon return.

func IsLocked(x *sync.Mutex) (locked bool) {

       if x.TryLock() {

              // x was unlocked but is now locked by us.

              x.Unlock()

              return false

       }

       // x was locked to start with.

       return true

}

 

I do understand that what I'm trying to achieve here is ok to do in only rare 
cases.  Indeed, I've only found a need for them and TryLock() on a few rare 
occasions.

 

Thanks,

 

John

 

    John Souvestre    New Orleans LA, USA    504-454-0899

 

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/001a01dc7c5a%247c025220%247406f660%24%40Souvestre.com.

Reply via email to