In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-06 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.