In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-09-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)05/31 Report--
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.
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.
The market share of Chrome browser on the desktop has exceeded 70%, and users are complaining about
The world's first 2nm mobile chip: Samsung Exynos 2600 is ready for mass production.According to a r
A US federal judge has ruled that Google can keep its Chrome browser, but it will be prohibited from
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
About us Contact us Product review car news thenatureplanet
More Form oMedia: AutoTimes. Bestcoffee. SL News. Jarebook. Coffee Hunters. Sundaily. Modezone. NNB. Coffee. Game News. FrontStreet. GGAMEN
© 2024 shulou.com SLNews company. All rights reserved.