Go Atomic count

Source: Internet
Author: User

By atomic counting, the same numeric value can be added and reduced in multi-threaded cases, which is generally used for state synchronization.

Look at the code first:

Package Main Import"FMT"Import" Time"Import"sync/atomic"Import"Runtime"Func Main () {//define an integervarOPS UInt64 =0 //Add value to OPS using 50 threads forI: =0; I < -; i++{go func () { for {//Add 1 each timeAtomic. AddUint64 (&ops,1) //This function is used for time slice switching//can be understood as the premium version of time. Sleep ()//avoid the previous for loop to put the CPU time slices in one thread so that other threads do not have the opportunity to executeRuntime. Gosched ()}} ()}//stop for a second, the top 50 threads have 1 seconds of execution timeTime . Sleep (time. Second)//Get Resultsopsfinal:= Atomic. LoadUint64 (&Ops) fmt. Println ("Ops:", opsfinal)}

The printing results are similar:

ops:40200

If you do not use an atomic count, using the OPS =ops+1 directly results in a multi-threaded count that is inaccurate.

Open go source in the atomic package, you can see the relevant algorithms are written in assembly language. So the atomic count performs very efficiently.

Go Atomic count

Related Article

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.