Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type TryLocker ¶
type TryLocker interface {
sync.Locker
// TryLock attempts to obtain a lock and times out if no lock
// can be obtained in the specified duration. A flag is returned
// indicating whether or not the lock was obtained.
TryLock(timeout time.Duration) bool
}
TryLocker represents an object that can be locked, unlocked, and implements a variant of its lock function that times out if no lock can be obtained in a specified duration.
type TryMutex ¶
TryMutex is a mutual exclusion lock that implements the TryLocker interface. The zero value for a TryMutex is an unlocked mutex.
A TryMutex may be copied after first use.
func (*TryMutex) Lock ¶
func (m *TryMutex) Lock()
Lock locks m. If the lock is already in use, the calling goroutine blocks until the mutex is available.
func (*TryMutex) TryLock ¶
TryLock attempts to lock m. If no lock can be obtained in the specified duration then a false value is returned.
Example ¶
package main
import (
"fmt"
"time"
"github.com/thecodeteam/gosync"
)
func main() {
// Assign a gosync.TryMutex to m and then lock it
var m gosync.TryMutex
m.Lock()
// Start a goroutine that sleeps for one second and then
// unlocks m. This makes it possible for the above TryLock
// call to lock m.
go func() {
time.Sleep(time.Duration(1) * time.Second)
m.Unlock()
}()
// Try for three seconds to lock m.
if m.TryLock(time.Duration(3) * time.Second) {
fmt.Println("lock obtained")
}
}
Output: lock obtained
Example (Timeout) ¶
package main
import (
"fmt"
"time"
"github.com/thecodeteam/gosync"
)
func main() {
// Assign a gosync.TryMutex to m and then lock m.
var m gosync.TryMutex
m.Lock()
// Try for three seconds to lock m.
if !m.TryLock(time.Duration(3) * time.Second) {
fmt.Println("lock not obtained")
}
}
Output: lock not obtained
Click to show internal directories.
Click to hide internal directories.