Documentation
¶
Index ¶
- Constants
- Variables
- func WithLock(lk sync.Locker, fn func())
- type ConditionVariable
- func (c *ConditionVariable) Broadcast()
- func (c *ConditionVariable) Signal()
- func (c *ConditionVariable) Wait(lck sync.Locker)
- func (c *ConditionVariable) WaitContext(ctx context.Context, lck sync.Locker) error
- func (c *ConditionVariable) WaitFor(lck sync.Locker, timeout time.Duration) error
- func (c *ConditionVariable) WaitForPred(lck sync.Locker, timeout time.Duration, pred func() bool) bool
- func (c *ConditionVariable) WaitPred(lck sync.Locker, pred func() bool)
- func (c *ConditionVariable) WaitPredContext(ctx context.Context, lck sync.Locker, pred func() bool) bool
- func (c *ConditionVariable) WaitUntil(lck sync.Locker, d time.Time) error
- func (c *ConditionVariable) WaitUntilPred(lck sync.Locker, d time.Time, pred func() bool) bool
- type EmptyThreadDoOption
- type Event
- type LruPool
- func (t *LruPool) CloseIdleResources()
- func (t *LruPool) Get(ctx context.Context, req interface{}) (v interface{}, put context.CancelFunc)
- func (t *LruPool) GetByKey(ctx context.Context, key interface{}, req interface{}) (v interface{}, put context.CancelFunc)
- func (t *LruPool) GetByKeyOrError(ctx context.Context, key interface{}, req interface{}) (pc *PersistResource, err error)
- func (t *LruPool) GetOrError(ctx context.Context, req interface{}) (v interface{}, put context.CancelFunc, err error)
- func (t *LruPool) Put(presource *PersistResource)
- func (t *LruPool) RemoveIdleResource(presource *PersistResource) bool
- type PersistResource
- type Subject
- type Thread
- type ThreadDoOption
- type ThreadDoOptionFunc
- type TimeoutCond
- func (c *TimeoutCond) Broadcast()
- func (c *TimeoutCond) Signal()
- func (c *TimeoutCond) Wait()
- func (c *TimeoutCond) WaitContext(ctx context.Context) error
- func (c *TimeoutCond) WaitFor(timeout time.Duration) error
- func (c *TimeoutCond) WaitForPred(timeout time.Duration, pred func() bool) bool
- func (c *TimeoutCond) WaitPred(pred func() bool)
- func (c *TimeoutCond) WaitPredContext(ctx context.Context, pred func() bool) bool
- func (c *TimeoutCond) WaitUntil(d time.Time) error
- func (c *TimeoutCond) WaitUntilPred(d time.Time, pred func() bool) bool
- type Until
- type Walk
- type WalkFunc
Examples ¶
Constants ¶
const DefaultMaxIdleResourcesPerBucket = 2
DefaultMaxIdleResourcesPerBucket is the default value of LruPool's MaxIdleResourcesPerBucket.
Variables ¶
var DefaultLruPool = &LruPool{ MaxIdleResources: 100, IdleResourceTimeout: 90 * time.Second, }
DefaultLruPool is new resources as needed and caches them for reuse by subsequent calls.
var ErrThreadClosed = errors.New("sync: Thread closed")
ErrThreadClosed is returned by the Thread's Do methods after a call to `Shutdown`.
var ErrUntilClosed = errors.New("sync: Until closed")
ErrUntilClosed is returned by the Until's Do method after a call to Close.
Functions ¶
Types ¶
type ConditionVariable ¶
type ConditionVariable struct {
// contains filtered or unexported fields
}
ConditionVariable is an object able to block the calling thread until notified to resume. see http://www.cplusplus.com/reference/condition_variable/condition_variable/
func (*ConditionVariable) Broadcast ¶
func (c *ConditionVariable) Broadcast()
Broadcast wakes all goroutines waiting on c.
It is allowed but not required for the caller to hold c.L during the call.
func (*ConditionVariable) Signal ¶
func (c *ConditionVariable) Signal()
Signal wakes one goroutine waiting on c, if there is any.
It is allowed but not required for the caller to hold c.L during the call.
func (*ConditionVariable) Wait ¶
func (c *ConditionVariable) Wait(lck sync.Locker)
Wait atomically unlocks c.L and suspends execution of the calling goroutine. After later resuming execution, Wait locks c.L before returning. Unlike in other systems, Wait cannot return unless awoken by Broadcast or Signal.
Because c.L is not locked when Wait first resumes, the caller typically cannot assume that the condition is true when Wait returns. Instead, the caller should Wait in a loop:
c.L.Lock() for !condition() { c.Wait() } ... make use of condition ... c.L.Unlock()
Wait wait until notified
func (*ConditionVariable) WaitContext ¶
WaitContext wait until notified or time point The execution of the current thread (which shall have locked lck's mutex) is blocked either until notified or until ctx done, whichever happens first.
func (*ConditionVariable) WaitFor ¶
WaitFor The execution of the current goroutine (which shall have locked lck's mutex) is blocked during rel_time, or until notified (if the latter happens first). WaitFor wait for timeout or until notified It behaves as if implemented as: return wait_until (lck, chrono::steady_clock::now() + rel_time);
func (*ConditionVariable) WaitForPred ¶
func (c *ConditionVariable) WaitForPred(lck sync.Locker, timeout time.Duration, pred func() bool) bool
WaitForPred wait for timeout or until notified If pred is nil, do as pred returns false always, If pred is specified, the function only blocks if pred returns false, and notifications can only unblock the thread when it becomes true (which is especially useful to check against spurious wake-up calls). It behaves as if implemented as: return wait_until (lck, chrono::steady_clock::now() + rel_time, std::move(pred));
func (*ConditionVariable) WaitPred ¶
func (c *ConditionVariable) WaitPred(lck sync.Locker, pred func() bool)
WaitPred wait until notified If pred is specified (2), the function only blocks if pred returns false, and notifications can only unblock the thread when it becomes true (which is specially useful to check against spurious wake-up calls). This version (2) behaves as if implemented as: while (!pred()) wait(lck);
func (*ConditionVariable) WaitPredContext ¶
func (c *ConditionVariable) WaitPredContext(ctx context.Context, lck sync.Locker, pred func() bool) bool
WaitPredContext wait until notified or ctx done The execution of the current thread (which shall have locked lck's mutex) is blocked either until notified or until ctx, whichever happens first. If pred is nil, do as pred returns false always, If pred is specified, the function only blocks if pred returns false, and notifications can only unblock the thread when it becomes true (which is especially useful to check against spurious wake-up calls). It behaves as if implemented as: while (!pred())
if ( wait_until(ctx,lck) == cv_status::timeout) return pred();
return true;
func (*ConditionVariable) WaitUntil ¶
WaitUntil wait until notified or time point The execution of the current thread (which shall have locked lck's mutex) is blocked either until notified or until abs_time, whichever happens first.
func (*ConditionVariable) WaitUntilPred ¶
WaitUntilPred wait until notified or ctx done The execution of the current thread (which shall have locked lck's mutex) is blocked either until notified or until ctx, whichever happens first. If pred is nil, do as pred returns false always, If pred is specified, the function only blocks if pred returns false, and notifications can only unblock the thread when it becomes true (which is especially useful to check against spurious wake-up calls). It behaves as if implemented as: while (!pred())
if ( wait_until(lck,abs_time) == cv_status::timeout) return pred();
return true;
type EmptyThreadDoOption ¶ added in v1.2.33
type EmptyThreadDoOption struct{}
EmptyThreadDoOption does not alter the configuration. It can be embedded in another structure to build custom options.
This API is EXPERIMENTAL.
type Event ¶
type Event struct {
// contains filtered or unexported fields
}
Event represents a one-time event that may occur in the future. we use a fast path to avoid the more-expensive "select" below after the Event has returned once.
func (*Event) Done ¶
func (e *Event) Done() <-chan struct{}
Done returns a channel that will be closed when Fire is called.
type LruPool ¶
type LruPool struct { // New optionally specifies a function to generate // a value when Get would otherwise return nil. // It may not be changed concurrently with calls to Get. New func(ctx context.Context, req interface{}) (resp interface{}, err error) // DisableKeepAlives, if true, disables keep-alives and // will only use the resource to the server for a single request. DisableKeepAlives bool // MaxIdleResources controls the maximum number of idle (keep-alive) // resources across all buckets. Zero means no limit. MaxIdleResources int // MaxIdleResourcesPerBucket, if non-zero, controls the maximum idle // (keep-alive) resources to keep per-bucket. If zero, // DefaultMaxIdleResourcesPerBucket is used. MaxIdleResourcesPerBucket int // MaxResourcesPerBucket optionally limits the total number of // resources per bucket, including resources in the newResource, // active, and idle states. On limit violation, news will block. // // Zero means no limit. MaxResourcesPerBucket int // IdleResourceTimeout is the maximum amount of time an idle // (keep-alive) resource will remain idle before closing // itself. // Zero means no limit. IdleResourceTimeout time.Duration // contains filtered or unexported fields }
LruPool is an implementation of sync.Pool with LRU.
By default, LruPool caches resources for future re-use. This may leave many open resources when accessing many buckets. This behavior can be managed using LruPool's CloseIdleResources method and the MaxIdleResourcesPerBucket and DisableKeepAlives fields.
LruPools should be reused instead of created as needed. LruPools are safe for concurrent use by multiple goroutines.
A LruPool is a low-level primitive for making resources.
func (*LruPool) CloseIdleResources ¶
func (t *LruPool) CloseIdleResources()
CloseIdleResources closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.
func (*LruPool) Get ¶
func (t *LruPool) Get(ctx context.Context, req interface{}) (v interface{}, put context.CancelFunc)
Get creates a new PersistResource to the target as specified in the key. If this doesn't return an error, the PersistResource is ready to write requests to.
func (*LruPool) GetByKey ¶
func (t *LruPool) GetByKey(ctx context.Context, key interface{}, req interface{}) (v interface{}, put context.CancelFunc)
GetByKey creates a new PersistResource to the target as specified in the key. If this doesn't return an error, the PersistResource is ready to write requests to.
func (*LruPool) GetByKeyOrError ¶
func (t *LruPool) GetByKeyOrError(ctx context.Context, key interface{}, req interface{}) (pc *PersistResource, err error)
GetByKeyOrError creates a new PersistResource to the target as specified in the key. If this doesn't return an error, the PersistResource is ready to write requests to.
func (*LruPool) GetOrError ¶
func (t *LruPool) GetOrError(ctx context.Context, req interface{}) (v interface{}, put context.CancelFunc, err error)
GetOrError creates a new PersistResource to the target as specified in the key. If this doesn't return an error, the PersistResource is ready to write requests to.
func (*LruPool) Put ¶
func (t *LruPool) Put(presource *PersistResource)
func (*LruPool) RemoveIdleResource ¶
func (t *LruPool) RemoveIdleResource(presource *PersistResource) bool
RemoveIdleResource marks presource as dead.
type PersistResource ¶
type PersistResource struct { // contains filtered or unexported fields } // isBroken reports whether this resource is in a known broken state.
PersistResource wraps a resource, usually a persistent one (but may be used for non-keep-alive requests as well)
func (*PersistResource) Get ¶
func (pc *PersistResource) Get() interface{}
func (*PersistResource) Put ¶
func (pc *PersistResource) Put()
type Subject ¶
type Subject struct {
// contains filtered or unexported fields
}
Subject implements a condition variable like with channel, a rendezvous point for goroutines waiting for or announcing the occurrence of an event.
The caller typically cannot assume that the condition is true when Subscribe chan returns. Instead, the caller should Wait in a loop:
time.After(timeout, c.PublishBroadcast()) // for timeout or periodic event c.PublishBroadcast() // for async notify event directly eventC, cancel := c.Subscribe() for !condition() { select{ case event, closed := <- eventC: ... make use of event ... } } ... make use of condition ...
func (*Subject) PublishBroadcast ¶
PublishBroadcast wakes all listeners waiting on c. PublishBroadcast blocks until event is received or dropped. event will be dropped if ctx is Done before event is received.
func (*Subject) PublishSignal ¶
PublishSignal wakes one listener waiting on c, if there is any. PublishSignal blocks until event is received or dropped.
func (*Subject) Subscribe ¶
func (s *Subject) Subscribe() (<-chan interface{}, context.CancelFunc)
Subscribe returns a channel that's closed when awoken by PublishSignal or PublishBroadcast. never be canceled. Successive calls to Subscribe return different values. The close of the Subscribe channel may happen asynchronously, after the cancel function returns.
type Thread ¶
type Thread struct { GoRoutine bool // Use thread as goroutine, that is without runtime.LockOSThread() // The Leak is published as a variable directly. GoroutineLeak *expvar_.Leak // represents whether goroutine is leaked, take effects if not nil OSThreadLeak *expvar_.Leak // represents whether runtime.LockOSThread is leaked, take effects if not nil HandlerLeak *expvar_.Leak // represents whether handler in Do is blocked is leaked, take effects if not nil // contains filtered or unexported fields }
Thread should be used for such as calling OS services or non-Go library functions that depend on per-thread state, as runtime.LockOSThread().
func (*Thread) Do ¶
func (t *Thread) Do(ctx context.Context, f func(), opts ...ThreadDoOption) error
Do will call the function f in the same thread or escape thread. f is enqueued only if ctx is not canceled and Thread is not Shutdown and Not escape
func (*Thread) WatchStats ¶ added in v1.2.50
func (t *Thread) WatchStats()
WatchStats bind Leak var to "sync.Thread"
type ThreadDoOption ¶ added in v1.2.33
type ThreadDoOption interface {
// contains filtered or unexported methods
}
A ThreadDoOption sets options.
func WiththreadDoEscapeThread ¶ added in v1.2.33
func WiththreadDoEscapeThread(v bool) ThreadDoOption
WiththreadDoEscapeThread sets EscapeThread in threadDo. call the function f in the same thread or escape thread
type ThreadDoOptionFunc ¶ added in v1.2.33
type ThreadDoOptionFunc func(*threadDo)
ThreadDoOptionFunc wraps a function that modifies threadDo into an implementation of the ThreadDoOption interface.
type TimeoutCond ¶
type TimeoutCond struct { // L is held while observing or changing the condition L sync.Locker // contains filtered or unexported fields }
func NewTimeoutCond ¶
func NewTimeoutCond(l sync.Locker) *TimeoutCond
NewTimeoutCond returns a new TimeoutCond with Locker l.
func (*TimeoutCond) Broadcast ¶
func (c *TimeoutCond) Broadcast()
Broadcast wakes all goroutines waiting on c.
It is allowed but not required for the caller to hold c.L during the call.
func (*TimeoutCond) Signal ¶
func (c *TimeoutCond) Signal()
Signal wakes one goroutine waiting on c, if there is any.
It is allowed but not required for the caller to hold c.L during the call.
func (*TimeoutCond) Wait ¶
func (c *TimeoutCond) Wait()
Wait atomically unlocks c.L and suspends execution of the calling goroutine. After later resuming execution, Wait locks c.L before returning. Unlike in other systems, Wait cannot return unless awoken by Broadcast or Signal.
Because c.L is not locked when Wait first resumes, the caller typically cannot assume that the condition is true when Wait returns. Instead, the caller should Wait in a loop:
c.L.Lock() for !condition() { c.Wait() } ... make use of condition ... c.L.Unlock()
Wait wait until notified
func (*TimeoutCond) WaitContext ¶
func (c *TimeoutCond) WaitContext(ctx context.Context) error
WaitContext wait until notified or time point The execution of the current thread (which shall have locked lck's mutex) is blocked either until notified or until ctx done, whichever happens first.
func (*TimeoutCond) WaitFor ¶
func (c *TimeoutCond) WaitFor(timeout time.Duration) error
WaitFor The execution of the current goroutine (which shall have locked lck's mutex) is blocked during rel_time, or until notified (if the latter happens first). WaitFor wait for timeout or until notified It behaves as if implemented as: return wait_until (lck, chrono::steady_clock::now() + rel_time);
func (*TimeoutCond) WaitForPred ¶
func (c *TimeoutCond) WaitForPred(timeout time.Duration, pred func() bool) bool
WaitForPred wait for timeout or until notified If pred is nil, do as pred returns false always, If pred is specified, the function only blocks if pred returns false, and notifications can only unblock the thread when it becomes true (which is especially useful to check against spurious wake-up calls). It behaves as if implemented as: return wait_until (lck, chrono::steady_clock::now() + rel_time, std::move(pred));
func (*TimeoutCond) WaitPred ¶
func (c *TimeoutCond) WaitPred(pred func() bool)
WaitPred wait until notified If pred is specified (2), the function only blocks if pred returns false, and notifications can only unblock the thread when it becomes true (which is specially useful to check against spurious wake-up calls). This version (2) behaves as if implemented as: while (!pred()) wait(lck);
func (*TimeoutCond) WaitPredContext ¶
func (c *TimeoutCond) WaitPredContext(ctx context.Context, pred func() bool) bool
WaitPredContext wait until notified or ctx done The execution of the current thread (which shall have locked lck's mutex) is blocked either until notified or until ctx, whichever happens first. If pred is nil, do as pred returns false always, If pred is specified, the function only blocks if pred returns false, and notifications can only unblock the thread when it becomes true (which is especially useful to check against spurious wake-up calls). It behaves as if implemented as: while (!pred())
if ( wait_until(ctx,lck) == cv_status::timeout) return pred();
return true;
func (*TimeoutCond) WaitUntil ¶
func (c *TimeoutCond) WaitUntil(d time.Time) error
WaitUntil wait until notified or time point The execution of the current thread (which shall have locked lck's mutex) is blocked either until notified or until abs_time, whichever happens first.
func (*TimeoutCond) WaitUntilPred ¶
func (c *TimeoutCond) WaitUntilPred(d time.Time, pred func() bool) bool
WaitUntilPred wait until notified or time point The execution of the current thread (which shall have locked c.L's mutex) is blocked either until notified or until abs_time, whichever happens first. If pred is nil, do as pred returns false always, If pred is specified, the function only blocks if pred returns false, and notifications can only unblock the thread when it becomes true (which is especially useful to check against spurious wake-up calls). It behaves as if implemented as: while (!pred())
if ( wait_until(lck,abs_time) == cv_status::timeout) return pred();
return true;
type Until ¶
type Until struct {
// contains filtered or unexported fields
}
Until represents a class of work and forms a namespace in which units of work can be executed with duplicate suppression. It blocks on certain Do actions and unblock when Retry is called.
func (*Until) Do ¶
func (u *Until) Do(ctx context.Context, fn func() (interface{}, error)) (val interface{}, err error)
Do executes and returns the results of the given function. It may block in the following cases: - the current fn is nil - the err returned by the current fn is not nil When one of these situations happens, Do blocks until the Retry is called.
type Walk ¶
type Walk struct { Burst int // Burst will be set to 1 if less than 1 // contains filtered or unexported fields }
Example ¶
package main import ( "context" "fmt" "github.com/searKing/golang/go/sync" ) func main() { // chan WalkInfo walkChan := make(chan interface{}, 0) p := sync.Walk{ Burst: 1, } defer p.Wait() p.Walk(context.Background(), walkChan, func(name interface{}) error { fmt.Printf("%s\n", name) return nil }) for i := 0; i < 5; i++ { walkChan <- fmt.Sprintf("%d", i) } close(walkChan) }
Output: 0 1 2 3 4
func (*Walk) TrySetError ¶
func (*Walk) Walk ¶
func (p *Walk) Walk(ctx context.Context, taskChan <-chan interface{}, procFn WalkFunc) (doneC <-chan struct{})
Walk will consume all tasks parallel and block until ctx.Done() or taskChan is closed. Walk returns a channel that's closed when work done on behalf of this walk should be canceled. Done may return nil if this walk can never be canceled. Successive calls to Done return the same value. The close of the Done channel may happen asynchronously, after the cancel function returns.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
Package leaderelection implements leader election of a set of endpoints.
|
Package leaderelection implements leader election of a set of endpoints. |