Go channel实现互斥锁

代码示例

package main

import (
	"fmt"
	"time"
)

//使用channel 实现互斥锁
type Mutex struct {
	ch chan struct{}
}


//初始化锁
func NewMutex() *Mutex {
	mu := &Mutex{make(chan struct{},1)}
	mu.ch <- struct{}{}
	return mu
}

/// 请求锁
func (m *Mutex) Lock()  {
	<- m.ch
}

//解锁
func (m *Mutex) Unlock()  {
	select {
	case m.ch<- struct{}{}:
	default:
		panic("unlock of unlocked mutex")
	}
}


//尝试获取锁
func (m *Mutex) TryLock() bool {
	select {
	case <-m.ch:
		return true
	default:

	}
	return false
}


//加入一个超时的设置
func (m *Mutex) LockTimeout(timeout time.Duration) bool {
	timer := time.NewTimer(timeout)
	select {
	case <-m.ch:
		timer.Stop()
		return true
	case <- timer.C:
		
	}
	return false
}

func (m *Mutex) IsLocked() bool {
	return len(m.ch) == 0
}


func main() {
	m := NewMutex()
	ok := m.TryLock()
	fmt.Printf("locked v %v\n",ok)
	m.Unlock()
	ok = m.TryLock()

	fmt.Printf("locked %v\n",ok)
	m.Unlock()
	ok1 := m.LockTimeout(time.Millisecond*100)
	fmt.Printf("%v\n",ok1)
}

  

posted @ 2021-01-22 12:47  pebblecome  阅读(591)  评论(0)    收藏  举报