怎麼實現tryLock(timeout int)的功能

codinghxl發表於2016-10-20

這是我自己嘗試寫的一個

package internal_struct

import (
    "sync/atomic"
    "time"
)

type MutexLock struct {
    i *int32
}

func NewMutexLock() *MutexLock {
    var i int32
    i = 0
    return &MutexLock{&i}
}

func (m *MutexLock) TryLock(timeout int) bool {
    t := timeout
    b := false
    for !b {
        b = atomic.CompareAndSwapInt32(m.i, 0, 1)
        if b {
            break
        }
        t--
        if t == 0 {
            break
        }
        time.Sleep(time.Millisecond)
    }
    return b
}

func (m *MutexLock) UnLock() {
    atomic.CompareAndSwapInt32(m.i, 1, 0)
}

測試程式碼

package internal_struct

import (
    "sync/atomic"
    "testing"
    "time"
)

func TestMutexLock_TryLock(t *testing.T) {
    mutex := NewMutexLock()
    t.Log(mutex.TryLock(1))
    t.Log(mutex.TryLock(1))
    mutex.UnLock()
    t.Log(mutex.TryLock(1))
}

func TestMutexLock_UnLock(t *testing.T) {
    mutex := NewMutexLock()
    t.Log(mutex.TryLock(1))
    mutex.UnLock()
    t.Log(mutex.TryLock(1))
}

func TestMutexLock_TryLock2(t *testing.T) {
    mutex := NewMutexLock()
    var tid int32 = 0
    i := 0
    for ; i <= 20; i++ {

        go func() {
            id := atomic.AddInt32(&tid, 1)
            f := mutex.TryLock(20)

            t.Log(id, "", time.Now(), "", "-->", f)
            time.Sleep(500*time.Millisecond)
            if f {
                t.Log(id, "", time.Now(), "", "-->unlock")
                mutex.UnLock()
            }
        }()

        time.Sleep(time.Millisecond * 50)
    }

    time.Sleep(10 * time.Second)
}

更多原創文章乾貨分享,請關注公眾號
  • 怎麼實現tryLock(timeout int)的功能
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章