Golang Once source code analysis

Source: Internet
Author: User

Sync. Once can implement a singleton mode to ensure sync. Once.do (f func ()) is executed only once and can initialize an instance singleton.

Sync for Golang 1.9. Once, the same as the Golang 1.10. Source code location: Sync\once.go.

Structural body

The once structure is defined as follows:

type Once struct {    m    Mutex    done uint32   // 初始值为0表示还未执行过,1表示已经执行过}

Do

func (o *Once) Do(f func()) {    // done==1表示已经执行过了,直接结束返回    if atomic.LoadUint32(&o.done) == 1 {        return    }    // 锁住对象,避免并发问题    o.m.Lock()    defer o.m.Unlock()    if o.done == 0 {        // 先将done设置为1,再执行f函数        defer atomic.StoreUint32(&o.done, 1)        f()    }}

It is important to note that the Execute F function is synchronous, which means there may be a blocking problem.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.