Home  >  Article  >  Backend Development  >  How to Implement a Thread-Safe Global Counter in a Highly Concurrent Go System?

How to Implement a Thread-Safe Global Counter in a Highly Concurrent Go System?

DDD
DDDOriginal
2024-10-31 16:36:01329browse

How to Implement a Thread-Safe Global Counter in a Highly Concurrent Go System?

Global Counter in a Highly Concurrent System

Question: How can I create a shared global counter that can be accessed by multiple goroutines without duplication in a highly concurrent system?

You mentioned referring to a previous question and trying to use a channel counter, which is generally not recommended for a shared counter. While it may work in some scenarios, it becomes problematic in high-concurrency situations.

Answer:

1. Atomic Package:

The most effective approach to implement a shared counter is through the atomic package provided by Go. Atomic operations ensure that changes to shared data are executed as a single indivisible action, effectively preventing race conditions.

Example:

<code class="go">import "sync/atomic"

var globalCounter int32 = 0 // Atomically updated counter

func IncrementCounter() {
    atomic.AddInt32(&globalCounter, 1) // Atomically increments the counter
}

func ReadCounter() int32 {
    return atomic.LoadInt32(&globalCounter) // Atomically reads the counter's value
}</code>

2. Synchronized Channel:

Another option is to use a synchronized channel to share the counter value. However, this approach is less efficient and introduces additional complexity.

Example:

<code class="go">var counter chan int = make(chan int, 1)

func IncrementCounter() {
    counter <- 1
}

func ReadCounter() int {
    return <-counter
}</code>

In the provided code snippet, you have implemented a thread-safe counter by utilizing a channel for value exchange. However, you should also consider thread-safe operations for resetting the value. A proper implementation would look like:

<code class="go">var addCounterChan chan int = make(chan int, 100)
var readCounterChan chan int = make(chan int, 100)

func AddCounter() {
    addCounterChan <- 1
}

func GetCount() int {
    return <-readCounterChan
}</code>

The above is the detailed content of How to Implement a Thread-Safe Global Counter in a Highly Concurrent Go System?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn