1 Star 0 Fork 0

siddontang / tlock

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
util.go 687 Bytes
一键复制 编辑 原始数据 按行查看 历史
siddontang 提交于 2015-04-10 17:08 . refactor, use rwmutex instead
package tlock
import (
"sync"
"sync/atomic"
"time"
)
func LockTimeout(m sync.Locker, timeout time.Duration) bool {
timer := time.NewTimer(timeout)
defer timer.Stop()
return LockWithTimer(m, timer)
}
func LockWithTimer(m sync.Locker, timer *time.Timer) bool {
done := make(chan bool, 1)
decided := new(int32)
go func() {
m.Lock()
if atomic.SwapInt32(decided, 1) == 0 {
done <- true
} else {
// If we already decided the result, and this thread did not win
m.Unlock()
}
}()
select {
case <-done:
return true
case <-timer.C:
if atomic.SwapInt32(decided, 1) == 1 {
// The other thread already decided the result
return true
}
return false
}
}
1
https://gitee.com/siddontang/tlock.git
git@gitee.com:siddontang/tlock.git
siddontang
tlock
tlock
master

搜索帮助