Untitled

mail@pastecode.io avatar
unknown
golang
a year ago
792 B
2
Indexable
Never
package main

import (
    "container/list"
    "sync"
)

type FIFOLock struct {
    mutex *sync.Mutex
    list *list.List
}

func NewFIFOLock() *FIFOLock {
    return &FIFOLock{mutex: &sync.Mutex{}, list: list.New()}
}

func (l *FIFOLock) Lock() {
    l.mutex.Lock()
    defer l.mutex.Unlock()

    newLock := &sync.Mutex{}
    element := l.list.PushBack(newLock)

    newLock.Lock()
    
    if previous := element.Prev(); previous != nil {
        prevLock := previous.Value.(*sync.Mutex)
        prevLock.Lock()
        prevLock.Unlock()
    }
}

func (l *FIFOLock) Lock() {
    l.mutex.Lock()
    defer l.mutex.Unlock()

    first := l.list.Front()
    firstLock := first.Value.(*sync.Mutex)

    l.list.Remove(first)

    firstLock.Unlock()
}