2024-06-05 20:10:03 +00:00
|
|
|
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
|
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
|
2022-03-10 09:44:48 +00:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync/atomic"
|
|
|
|
)
|
|
|
|
|
|
|
|
// TryLock implement the classic "try-lock" operation.
|
|
|
|
type TryLock struct {
|
|
|
|
n int32
|
|
|
|
}
|
|
|
|
|
|
|
|
// Lock tries to lock the try-lock. If successful, it returns true.
|
2024-05-15 23:15:00 +00:00
|
|
|
// Otherwise, it returns false immediately.
|
2022-03-10 09:44:48 +00:00
|
|
|
func (c *TryLock) Lock() error {
|
|
|
|
if !atomic.CompareAndSwapInt32(&c.n, 0, 1) {
|
|
|
|
return errDoubleLock
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unlock unlocks the try-lock.
|
|
|
|
func (c *TryLock) Unlock() {
|
|
|
|
atomic.StoreInt32(&c.n, 0)
|
|
|
|
}
|