目錄
✅ Example 2: Using atomic.AddInt64 and atomic.LoadInt64 (Pre-Go 1.19 style)
✅ Example 3: Atomic Counter with Read (Load) and Write (Store)
❌ What Happens Without Atomic?
When to Use Atomic Counters
Summary
首頁 後端開發 Golang 原子計數器以身作則

原子計數器以身作則

Jul 27, 2025 am 03:27 AM
php java 程式設計

原子計數器用於在多個goroutine中安全地增減或讀取值以避免競爭條件,Go中的sync/atomic包提供底層原子操作,推薦使用atomic.Int64(Go 1.19 )或atomic.AddInt64/LoadInt64等函數實現;1. 使用atomic.Int64可安全實現並發自增,如10個goroutine各增100次最終結果為1000;2. 在舊版Go中可通過atomic.AddInt64(&counter, 1)和atomic.LoadInt64(&counter)操作int64類型變量實現等效功能,需確保使用int64而非int以保證原子性;3. 可結合Load和Add在監控場景中安全讀寫計數器,如後台定期打印訪問量同時主線程增加計數;若未使用原子操作而直接對普通int變量進行並發遞增,則會觸發競態條件,導致結果不准確並被-go run -race檢測出問題;應使用原子計數器的場景包括:僅執行簡單增減查存操作、追求高性能且無需複雜共享狀態;反之當需更新多個關聯變量或執行複合邏輯時應改用sync.Mutex;總結:原子計數器是並發安全、高效無鎖且易於使用的工具,只要確保類型為int64、避免混合非原子操作並利用-race標誌檢測問題,即可正確高效地處理跨goroutine計數需求。

atomic counters go by example

Atomic counters are used when you need to safely increment, decrement, or read a value from multiple goroutines without causing race conditions. In Go, the sync/atomic package provides low-level atomic operations, and atomic.Int64 (available since Go 1.19) or atomic.Value with int64 via atomic.AddInt64 , atomic.LoadInt64 , etc., are common ways to implement atomic counters.

atomic counters go by example

Let's walk through a few practical examples that show how atomic counters work and when to use them.


✅ Example 1: Simple Atomic Counter with atomic.Int64

Since Go 1.19, atomic.Int64 provides a clean, type-safe way to manage atomic counters.

atomic counters go by example
 package main

import (
    "fmt"
    "sync"
    "sync/atomic"
    "time"
)

func main() {
    var counter atomic.Int64
    var wg sync.WaitGroup

    // Launch 10 goroutines that each increment the counter 100 times
    for i := 0; i < 10; i {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for j := 0; j < 100; j {
                counter.Add(1)
                time.Sleep(time.Microsecond) // Simulate small work
            }
        }()
    }

    wg.Wait()
    fmt.Println("Final counter value:", counter.Load())
}

Output:

 Final counter value: 1000

✅ This is safe and race-free. No mutex needed.

atomic counters go by example

✅ Example 2: Using atomic.AddInt64 and atomic.LoadInt64 (Pre-Go 1.19 style)

If you're on an older Go version or prefer explicit functions:

 package main

import (
    "fmt"
    "sync"
    "sync/atomic"
)

func main() {
    var counter int64 // Must be int64 for atomic operations
    var wg sync.WaitGroup

    for i := 0; i < 5; i {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for j := 0; j < 200; j {
                atomic.AddInt64(&counter, 1)
            }
        }()
    }

    wg.Wait()
    fmt.Println("Counter:", atomic.LoadInt64(&counter))
}

? Note: You must use int64 (not int ) because the atomic package operates on specific sizes, and int may be 32-bit on some systems.


✅ Example 3: Atomic Counter with Read (Load) and Write (Store)

You can also safely read and write values atomically:

 package main

import (
    "fmt"
    "sync/atomic"
    "time"
)

func main() {
    var visits atomic.Int64

    // Simulate a background monitor
    go func() {
        for {
            time.Sleep(500 * time.Millisecond)
            fmt.Println("Visits so far:", visits.Load())
        }
    }()

    // Simulate incoming requests
    for i := 0; i < 10; i {
        visits.Add(1)
        time.Sleep(100 * time.Millisecond)
    }

    time.Sleep(time.Second) // Let monitor print a few times
}

This shows how you can safely read a counter from one goroutine while writing from others.


❌ What Happens Without Atomic?

If you use a regular int and increment across goroutines:

 var counter int
for i := 0; i < 10; i {
    go func() {
        for j := 0; j < 100; j {
            counter // ? Not atomic! Race condition!
        }
    }()
}

Run this with -race :

 go run -race main.go

You'll see race condition warnings , and the final value may be less than expected.


When to Use Atomic Counters

Use atomic counters when:

  • You're doing simple operations: increment, decrement, add, load, store.
  • Performance matters — atomics are faster than mutexes.
  • You don't need complex shared state (eg, updating multiple fields together).

Avoid atomics when:

  • You're updating multiple related variables — use sync.Mutex instead.
  • You need complex logic or consistency across values.

Summary

Atomic counters in Go are:

  • Safe for concurrent access
  • Efficient (no locks)
  • Easy to use with atomic.Int64 or atomic.AddInt64 / LoadInt64

Just remember:

  • Use int64 (not int )
  • Don't mix atomic and non-atomic access
  • Use -race flag to detect issues

Basically, if you're counting things across goroutines, reach for atomic.Int64 . It's simple, fast, and correct.

以上是原子計數器以身作則的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Laravel Lazy Loading與急切的加載 Laravel Lazy Loading與急切的加載 Jul 28, 2025 am 04:23 AM

懶加載在訪問關聯時才查詢,易導致N 1問題,適合不確定是否需要關聯數據的場景;2.急加載使用with()提前加載關聯數據,避免N 1查詢,適合批量處理場景;3.應優先使用急加載優化性能,可通過LaravelDebugbar等工具檢測N 1問題,並謹慎使用模型的$with屬性以避免不必要的性能開銷。

PHP中的對象關聯映射(ORM)性能調整 PHP中的對象關聯映射(ORM)性能調整 Jul 29, 2025 am 05:00 AM

避免N 1查詢問題,通過提前加載關聯數據來減少數據庫查詢次數;2.僅選擇所需字段,避免加載完整實體以節省內存和帶寬;3.合理使用緩存策略,如Doctrine的二級緩存或Redis緩存高頻查詢結果;4.優化實體生命週期,定期調用clear()釋放內存以防止內存溢出;5.確保數據庫索引存在並分析生成的SQL語句以避免低效查詢;6.在無需跟踪變更的場景下禁用自動變更跟踪,改用數組或輕量模式提升性能。正確使用ORM需結合SQL監控、緩存、批量處理和適當優化,在保持開發效率的同時確保應用性能。

深入了解PHP的內部垃圾收集機制 深入了解PHP的內部垃圾收集機制 Jul 28, 2025 am 04:44 AM

PHP的垃圾回收機制基於引用計數,但循環引用需靠週期性運行的循環垃圾回收器處理;1.引用計數在變量無引用時立即釋放內存;2.循環引用導致內存無法自動釋放,需依賴GC檢測並清理;3.GC在“可能根”zval達閾值或手動調用gc_collect_cycles()時觸發;4.長期運行的PHP應用應監控gc_status()、適時調用gc_collect_cycles()以避免內存洩漏;5.最佳實踐包括避免循環引用、使用gc_disable()優化性能關鍵區及通過ORM的clear()方法解引用對象,最

無服務器革命:使用BREF部署可擴展的PHP應用程序 無服務器革命:使用BREF部署可擴展的PHP應用程序 Jul 28, 2025 am 04:39 AM

Bref使PHP開發者能無需管理服務器即可構建可擴展、成本高效的應用。 1.Bref通過提供優化的PHP運行時層,將PHP帶入AWSLambda,支持PHP8.3等版本,並與Laravel、Symfony等框架無縫集成;2.部署步驟包括:使用Composer安裝Bref,配置serverless.yml定義函數和事件,如HTTP端點和Artisan命令;3.執行serverlessdeploy命令即可完成部署,自動配置APIGateway並生成訪問URL;4.針對Lambda限制,Bref提供解決

什麼是Laravel Octane? 什麼是Laravel Octane? Jul 28, 2025 am 04:12 AM

laraveloctaneisperformance-boostingpackagethatimprovesponseTimes和throughputbyservinglaraveravelavelaverablapplicationsviaswoole,opensWoole,orroadrunner.1.unliketraditionalphp-fpm

將PHP與機器學習模型集成 將PHP與機器學習模型集成 Jul 28, 2025 am 04:37 AM

usearestapitobridgephpandmlmodelsbyrunningthemodelinpythonviaflaskorfastapiandcallingitfromphpusingcurlorguzzle.2.runpythonscriptsdirectsdirectlyectlyectlyfromphpsingexec()orshell_exec()orshell_exec()orshell_exec()

在PHP中構建不變的物體,並具有可讀的屬性 在PHP中構建不變的物體,並具有可讀的屬性 Jul 30, 2025 am 05:40 AM

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

什麼是Laravel Octane,什麼時候有用? 什麼是Laravel Octane,什麼時候有用? Jul 28, 2025 am 04:13 AM

LaravelOctaneisusefulforimprovingperformanceinhigh-traffic,low-latency,orreal-timeapplicationsbykeepingtheLaravelframeworkloadedinmemoryusingSwooleorRoadRunner.1.Itexcelsinhigh-trafficapplicationsbyreducingserverloadandresponsetimethroughpersistentap

See all articles