Documentation
¶
Overview ¶
Package sync provides extra synchronization facilities such as semaphore in addition to the standard sync package.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Semaphore ¶
type Semaphore struct {
// contains filtered or unexported fields
}
Semaphore is a mimic of the POSIX semaphore based on channel and sync.Mutex. It could be used to limit the number of concurrent running goroutines. Basic example:
// Creates a ready-to-use semaphore sema := concurrent.NewSemaphore(InitValue) // Decrements the semaphore, blocks if value of the semaphore is less than 1 semaResource := sema.Acquire() // Increments the semaphore. If the semaphore's value consequently becomes greater than zero, // then another goroutine blocked in sema.Acquire() will be woken up and acquire the resources. semaResource.Release()
func NewSemaphore ¶
NewSemaphore creates a ready-to-use Semaphore.
value: Initial value of the Semaphore.
Example ¶
This example shows the basic usage of Semaphore.
package main
import (
"github.com/antigloss/go/sync"
"time"
)
func main() {
// Create a ready-to-use semaphore
sema := sync.NewSemaphore(10)
// Block to acquire resources from the semaphore
semaResource := sema.Acquire()
// Release resources acquired from a semaphore
semaResource.Release()
// Try to acquire resources from the semaphore, returns nil if resources cannot be acquired immediately
semaResource = sema.TryAcquire()
if semaResource != nil {
// Release resources acquired from a semaphore
semaResource.Release()
}
// Wait at most 2 seconds to acquire resources from the semaphore, returns nil if resources cannot be acquired after timeout
semaResource = sema.TimedAcquire(2 * time.Second)
if semaResource != nil {
// Release resources acquired from a semaphore
semaResource.Release()
}
}
func (*Semaphore) Acquire ¶
func (s *Semaphore) Acquire() *SemaphoreResource
Acquire decrements the semaphore, blocks if value of the semaphore is less than 1.
func (*Semaphore) TimedAcquire ¶
func (s *Semaphore) TimedAcquire(duration time.Duration) (sr *SemaphoreResource)
TimedAcquire waits at most a given time to decrement the semaphore. It returns nil if the decrement cannot be done after the given timeout.
func (*Semaphore) TryAcquire ¶
func (s *Semaphore) TryAcquire() (sr *SemaphoreResource)
TryAcquire tries to decrement the semaphore. It returns nil if the decrement cannot be done immediately.
type SemaphoreResource ¶
type SemaphoreResource struct {
// contains filtered or unexported fields
}
SemaphoreResource holds resources acquired from a Semaphore object.
func (*SemaphoreResource) Release ¶
func (sr *SemaphoreResource) Release()
Release releases resources acquired from a Semaphore object.