Last active
May 12, 2016 15:13
-
-
Save dermesser/f8c81266541837a9b4c6f9821a7e295f to your computer and use it in GitHub Desktop.
A way to use Mutex-like locking in Go, but with timeouts.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package play1 | |
import ( | |
"errors" | |
"time" | |
) | |
type MyStruct struct { | |
m map[string]uint64 | |
} | |
type SynchronizedMyStruct struct { | |
lock chan MyStruct | |
} | |
func NewSynchronizedMyStruct(ms MyStruct) SynchronizedMyStruct { | |
ch := make(chan MyStruct, 1) | |
ch <- ms | |
return SynchronizedMyStruct{lock: ch} | |
} | |
func (sms *SynchronizedMyStruct) Acquire() MyStruct { | |
return <-sms.lock | |
} | |
func (sms *SynchronizedMyStruct) AcquireWithTimeout(d time.Duration) (MyStruct, error) { | |
select { | |
case ms := <-sms.lock: | |
return ms, nil | |
case <-time.After(d): | |
return MyStruct{}, errors.New("timed out") | |
} | |
} | |
func (sms *SynchronizedMyStruct) Release(ms MyStruct) { | |
sms.lock <- ms | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment