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