There was a long thread just recently about SpinLocks and the memory model.
There are several implementations on github. I cannot vouch for the quality
of any of them.

fre 21 okt. 2016 kl 16:14 skrev Roberto Zanotto <robyz...@gmail.com>:

> Maybe you can solve this with atomics.
> You keep an int32 that acts as mutex (0 is unocked, 1 is locked),
> the Trylock is done with atomic.CompareAndSwapInt32(mu, 0, 1) and the
> Unlock with atomic.StoreInt32(mu, 0).
> This gives you a Trylock, but you lose the standard (blocking) Lock.
>
> You may have to put your "usage" variable inside an atomic.Value,
> if some goroutines want to read it while another is modifying it.
> Be sure to test your code with -race.
>
>
> On Friday, October 21, 2016 at 3:05:10 PM UTC+2, Michael Liu wrote:
>
> I've a race scenario used with Mutex.Lock with Lock() and Unlock(). now
> multi-routines try to lock the resource and start a few logical code if the
> Lock.Lock() succesfully. other routines don't need to block util
> Lock.Unlock() that they can do the above logicals with next time or in
> future(logical may changes some variables and those variables' change could
> be see with latency). That looks like a Trylock() implemetion.
> I browsed the discussion
> https://groups.google.com/forum/#!searchin/golang-nuts/trylock%7Csort:relevance/golang-nuts/MTaJNZ49u60/ycc7UHgjLwgJ
> <https://groups.google.com/forum/#!searchin/golang-nuts/trylock%7Csort:relevance/golang-nuts/MTaJNZ49u60/ycc7UHgjLwgJ>and
> guess Trylock() may the best way ...
>
> var lock sync.Mutex
>
> func change(vvv int) bool {
>      if lock.Trylock() {
>           // execute codes if we trylock successfully
>           bla bla.......
>           usage := vvv .......
>           bla bla.......
>
>           return true
>      } else {
>           // someone is locking the resource. we skip the
>           // change(vvvv) call. and take a chance in next
>           // time. the context of this method we can drop
>           // directly
>
>           return false
>      }
> }
>
> routines := 16
>
> for ;routines != 0; routines-- {
>     go func() {
>         // infinite loop
>         var i = 0
>         for {
>             // discard the return value of change()
>             change(i)
>             i++
>         }
>     }()
> }
>
> --
> 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 golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
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 golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to