Get the App
SLTechnology News&Howtos  ›  Database  › 

How to use Once in Go language

Shulou Source: shulou.com Published: 2022-05-31 18:58:17 09月10日 Update

Go language how to use Once, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Sync.Once is an object in the sync package that has only one method, Do, which is so special that it is executed only once, no matter how many times it is called while the program is running.

1. Applicable scenarios:

In a process, if a part of the code in a function wants to be executed only once when many co-routines are executed, then Once works. For example: initialize the shared memory in the process, which only wants to be initialized once by the process, and other coprograms do not need initialization operations.

Example:

Result analysis:

As you can see from the output above, the code in the onceBody () function is called only once after using once.Do. The other protocols are still running, but the code in the onceBody () function is not executed.

two。 The source code is as follows:

The data structure and function implementation of Once are as follows:

Note: cleverly, in the doSlow function, the self-increment operation of the counter done is written into the defer function, because the function in defer will be executed even when it is in panic, which can effectively avoid the failure of the counter of the Do function when panic, resulting in other coprograms calling the code in f () once.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Tags: Function code time process method result counter help run language ingenious effective clear special middle function example memory content reason Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Huawei MySQL OPPO Reno NVidia