Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the simpler concurrent code?

2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "what is the simpler concurrent code?" in the actual case operation process, many people will encounter such a dilemma, and then let the editor lead you to learn how to deal with these situations! I hope you can read it carefully and be able to achieve something!

Name functions AtomicBoolbool type atomic class AtomicDurationDuration about atomic class AtomicFloat64float64 type atomic class Barrier fence [wrapper will be unlocked and unlocked] Cond condition variable DoneChan elegant notification closes resources Limit control requests that will not be modified after ImmutableResource creation LockedCalls ensures serial calls to ManagedResource resource management Once provides once funcOnceGuard disposable resource management Poolpool Simple pool RefResource reference counting resource ResourceManager explorer SharedCalls similar to singflight function SpinLock spin lock: spin + CASTimeoutLimitLimit + timeout control

Let's start to introduce the above library components respectively.

Atomic

Because there is no generic support, there are many types of atomic class support. The following uses float64 as an example:

Func (f * AtomicFloat64) Add (val float64) float64 {for {old: = f.Load () nv: = old + val if f.CompareAndSwap (old, nv) {return nv}} func (f * AtomicFloat64) CompareAndSwap (old, val float64) bool {return atomic.CompareAndSwapUint64 ((* uint64) (f) Math.Float64bits (old), math.Float64bits (val)} func (f * AtomicFloat64) Load () float64 {return math.Float64frombits (atomic.LoadUint64 ((* uint64) (f))} func (f * AtomicFloat64) Set (val float64) {atomic.StoreUint64 ((* uint64) (f), math.Float64bits (val))}

Add (val): if CAS fails, keep for loop retry, get old val, and set old+val

CompareAndSwap (old, new): CAS that calls the underlying atomic

Load (): call atomic.LoadUint64 and then convert

Set (val): call atomic.StoreUint64

As for other types, developers want to expand the types they want, according to the above, basically call the original atomic operation, and then convert to the desired type, for example: when you encounter bool, you can distinguish the corresponding false and true with the help of 0,1.

Barrier

Here, Barrier only encapsulates the operation of the business function and passes it in as a closure, and internally solves the locking and unlocking of the lock operation by itself. [prevent developers from locking and forgetting to unlock]

Func (b * Barrier) Guard (fn func ()) {b.lock.Lock () defer b.lock.Unlock () / / your own business logic fn ()} Cond/Limit/TimeoutLimit

Together with Limit, this data structure forms TimeoutLimit. Here we will talk about these three together:

Func NewTimeoutLimit (n int) TimeoutLimit {return TimeoutLimit {limit: NewLimit (n), cond: NewCond (),}} func NewLimit (n int) Limit {return Limit {pool: make (chan lang.PlaceholderType, n),}}

Limit, this is buffered channel.

Cond is unbuffered

Therefore, the name is understood here: because Limit restricts the use of a certain resource, you need to put a preset number of resources in the resource pool in advance; Cond is like a valve, which requires both sides to be ready for data exchange, so unbuffered and synchronous control is used.

Here we look at the management of session in stores/mongo to understand resource control:

Func (cs * concurrentSession) takeSession (opts... Option) (* mgo.Session, error) {/ / option parameter injection. / / see if the resource if err: = cs.limit.Borrow (o.timeout) can still be fetched from the limit. Err! = nil {return nil, err} else {return cs.Copy (), nil}} func (l TimeoutLimit) Borrow (timeout time.Duration) error {/ / 1. If there are still resources in limit, take one out and return if l.TryBorrow () {return nil} / / 2. If the resources in limit have been used up, var ok bool for {/ / only cond can fetch one [no cache, and only cond ref--; if ref = = 0-> ref clean.

Func (r * RefResource) Use () error {/ / mutually exclusive access r.lock.Lock () defer r.lock.Unlock () / clear the tag if r.cleaned {return ErrUseOfCleaned} / / reference + 1 r.refraction + return nil} SharedCalls

In a word: using SharedCalls can make multiple requests only need to make one call to get the result at the same time, and other requests can "enjoy the success". This design effectively reduces the concurrency pressure on resource services and can effectively prevent cache breakdown.

This component is repeatedly applied to other components, the ResourceManager mentioned above.

Similarly, SharedCalls caching can be used when high-frequency concurrent access to a resource is required.

/ / when multiple requests request resources using the Do method at the same time, func (g * sharedGroup) Do (key string, fn func () (interface {}, error)) (interface {}, error) {/ / first apply for locking g.lock.Lock () / / get the corresponding call result according to key, and save if c, ok: = g.calls [key] with variable c After ok {/ / gets the call, release the lock. Here the call may not have the actual data, but an empty memory occupancy g.lock.Unlock () / / calls wg.Wait to determine whether other goroutine is applying for resources. If it is blocked, it means that other goroutine is acquiring resources c.wg.Wait () / / when the wg.Wait is no longer blocking, indicating that resource acquisition has ended. You can return the result return c.val directly. If c.err} / / does not get the result, call the makeCall method to get the resources. Note that only one goroutine can call makecall c: = g.makeCall (key, fn) / / return the call result return c.val. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report