Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Example Analysis of sync.Once in golang

Shulou Source: shulou.com Published: 2022-06-01 13:27:30 09月27日 Update

This article will explain in detail the example analysis of sync.Once in golang. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Sync.once can control that the function can only be called once and cannot be called repeatedly.

We can implement a thread-safe singleton pattern with the following code

Package singleton

Import (

"fmt"

"sync"

)

Type object struct {

Name string

}

Var once sync.Once

Var obj * object / / Singleton pointer

/ / expose method outsourcing calls

Func Instance () * object {

Once.Do (getObj)

Return obj

}

Func getObj () {

If obj = = nil {

Obj = new (object)

/ / other initialization events can be done

}

}

/ / singleton test

Func (obj * object) Test () {

Fmt.Println (obj.name)

}

What if we want to implement such a function ourselves?

Define a status variable to describe whether it has been executed

Use sync.Mutex or sync.Atomic to obtain the status state safely and determine whether to execute a specific function according to the state.

Then take a look at how sync.Once is actually implemented.

/ / Once is an object that will perform exactly one action.

Type Once struct {

M Mutex

Done uint32

}

/ / double-layer checking mechanism is used

Func (o * Once) Do (f func ()) {

If atomic.LoadUint32 (& o.done) = = 1 {

Return

}

/ / Slow-path.

O.m.Lock ()

Defer o.m.Unlock ()

/ / it needs to be rejudged here, because it is possible for other gotoutine to change the state value of status between the state value taken out by atomic.LoadUint32 and o.m.Lock ().

If o.done = = 0 {

F ()

Atomic.StoreUint32 (& o.done, 1)

}

}

Some netizens have written more concise code, do not know why the official did not adopt the following implementation.

Type Once struct {

Done int32

}

Func (o * Once) Do (f func ()) {

If atomic.LoadInt32 (& o.done) = = 1 {

Return

}

/ / Slow-path.

If atomic.CompareAndSwapInt32 (& o.done, 0,1) {

F ()

}

} this is the end of the article on "sample Analysis of sync.Once in golang". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: State article example analysis security code function more state value thread faceted good practical concise between event content again function double layer Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info MySQL macOS MariaDB Redmi