华尔街英语品牌大使开启中国之旅
Avoid shared mutable state by using channels to pass data instead of direct access, as demonstrated with a channel-based counter that eliminates race conditions. 2. Use sync.Mutex or sync.RWMutex to protect shared state like caches or configs, ensuring all access paths are properly locked while avoiding coarse locking. 3. Apply sync/atomic for simple atomic operations on basic types such as counters, using functions like atomic.AddUint64 and atomic.LoadUint64 for lock-free performance. 4. Carry request-scoped data safely across goroutines using context.Context with custom key types to prevent collisions. 5. Favor immutable data structures when sharing data to eliminate the need for synchronization, creating new copies instead of modifying existing ones. The best practices emphasize intentional design: prefer channels, use mutexes and atomics appropriately, leverage context, embrace immutability, and never assume package-level variables are safe under concurrency, always testing with the race detector.
Managing state in concurrent Go applications is one of the most common sources of bugs—especially data races—if not handled carefully. Go encourages concurrency through goroutines and channels, but sharing mutable state across them requires deliberate design. Here’s how to do it right.

1. Avoid Shared Mutable State When Possible
The best way to manage state in concurrent programs is to avoid sharing it altogether. Go’s concurrency philosophy, summarized by the slogan "Do not communicate by sharing memory; share memory by communicating," encourages using channels to pass data between goroutines instead of letting them access the same variables directly.
Example: Using a channel instead of a shared counter

func worker(ch chan int) { for i := 0; i < 1000; i { ch <- 1 } close(ch) } func main() { ch := make(chan int) go worker(ch) sum := 0 for val := range ch { sum = val } fmt.Println("Total:", sum) // 1000 }
Here, the accumulator (sum
) lives in one goroutine, and values are sent over a channel. No mutexes, no race conditions.
2. Use sync.Mutex
for Controlled Access
When you must share state—like a global config, cache, or session store—protect it with a sync.Mutex
or sync.RWMutex
.

Example: Thread-safe map with mutex
type SafeCounter struct { mu sync.RWMutex count map[string]int } func (c *SafeCounter) Inc(key string) { c.mu.Lock() defer c.mu.Unlock() c.count[key] } func (c *SafeCounter) Value(key string) int { c.mu.RLock() defer c.mu.RUnlock() return c.count[key] }
Use RWMutex
when reads are frequent and writes are rare—readers can proceed concurrently, but writers get exclusive access.
?? Common mistake: Forgetting to lock in all code paths, or locking too coarsely (e.g., locking the entire function when only a few lines need protection).
3. Use sync/atomic
for Simple Values
For low-level primitives like integers or pointers, sync/atomic
provides efficient, lock-free operations. It’s ideal for counters, flags, or sequence generators.
Example: Atomic increment
var ops uint64 for i := 0; i < 50; i { go func() { for j := 0; j < 1000; j { atomic.AddUint64(&ops, 1) } }() } time.Sleep(2 * time.Second) fmt.Println("ops:", atomic.LoadUint64(&ops))
- Functions like
atomic.AddX
,atomic.LoadX
,atomic.StoreX
, andatomic.SwapX
are available for various types. - Avoid using
atomic
for complex data structures—it’s meant for simple types only.
4. Leverage context.Context
for Request-Scoped State
When handling HTTP requests or long-running operations, use context.Context
to carry request-scoped data (e.g., user IDs, deadlines, trace IDs) across goroutines safely.
ctx := context.WithValue(context.Background(), "userID", "123") go func(ctx context.Context) { if userID, ok := ctx.Value("userID").(string); ok { fmt.Println("User:", userID) } }(ctx)
? Best practice: Use custom types for keys to avoid collisions.
type ctxKey string const userIDKey ctxKey = "user-id" // Set: ctx := context.WithValue(parent, userIDKey, "456") // Get: ctx.Value(userIDKey).(string)
Bonus: Use Immutable Data Structures
When sharing data between goroutines, consider making it immutable. Once created, it can be safely read by any number of goroutines without synchronization.
For example, instead of modifying a config struct, create a new copy:
type Config struct { Timeout time.Duration Debug bool } func (c Config) WithDebug(v bool) Config { c.Debug = v // Copy is modified return c }
Now you can pass copies safely across goroutines.
Summary of Best Practices
- ? Prefer channels over shared memory.
- ? Use
sync.Mutex
orsync.RWMutex
when sharing mutable state. - ? Use
sync/atomic
for simple, high-performance counters. - ? Carry request-scoped data via
context.Context
. - ? Favor immutability when possible.
- ? Don’t assume package-level variables are safe to access from multiple goroutines.
Concurrent state management in Go doesn’t have to be complex—just intentional. Use the right tool for the job, and always test with the race detector (go run -race
).
The above is the detailed content of State Management in Concurrent Go Applications. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go's switch statement will not be executed throughout the process by default and will automatically exit after matching the first condition. 1. Switch starts with a keyword and can carry one or no value; 2. Case matches from top to bottom in order, only the first match is run; 3. Multiple conditions can be listed by commas to match the same case; 4. There is no need to manually add break, but can be forced through; 5.default is used for unmatched cases, usually placed at the end.

Usecontexttopropagatecancellationanddeadlinesacrossgoroutines,enablingcooperativecancellationinHTTPservers,backgroundtasks,andchainedcalls.2.Withcontext.WithCancel(),createacancellablecontextandcallcancel()tosignaltermination,alwaysdeferringcancel()t

Use a dedicated and reasonably configured HTTP client to set timeout and connection pools to improve performance and resource utilization; 2. Implement a retry mechanism with exponential backoff and jitter, only retry for 5xx, network errors and 429 status codes, and comply with Retry-After headers; 3. Use caches for static data such as user information (such as sync.Map or Redis), set reasonable TTL to avoid repeated requests; 4. Use semaphore or rate.Limiter to limit concurrency and request rates to prevent current limit or blocking; 5. Encapsulate the API as an interface to facilitate testing, mocking, and adding logs, tracking and other middleware; 6. Monitor request duration, error rate, status code and retry times through structured logs and indicators, combined with Op

To correctly copy slices in Go, you must create a new underlying array instead of directly assigning values; 1. Use make and copy functions: dst:=make([]T,len(src));copy(dst,src); 2. Use append and nil slices: dst:=append([]T(nil),src...); both methods can realize element-level copying, avoid sharing the underlying array, and ensure that modifications do not affect each other. Direct assignment of dst=src will cause both to refer to the same array and are not real copying.

Use the template.ParseFS and embed package to compile HTML templates into binary files. 1. Import the embed package and embed the template file into the embed.FS variable with //go:embedtemplates/.html; 2. Call template.Must(template.ParseFS(templateFS,"templates/.html")))) to parse all matching template files; 3. Render the specified in the HTTP processor through tmpl.ExecuteTemplate(w,"home.html", nil)

Go uses time.Time structure to process dates and times, 1. Format and parse the reference time "2025-08-0415:04:05" corresponding to "MonJan215:04:05MST2006", 2. Use time.Date(year, month, day, hour, min, sec, nsec, loc) to create the date and specify the time zone such as time.UTC, 3. Time zone processing uses time.LoadLocation to load the position and use time.ParseInLocation to parse the time with time zone, 4. Time operation uses Add, AddDate and Sub methods to add and subtract and calculate the interval.

To import local packages correctly, you need to use the Go module and follow the principle of matching directory structure with import paths. 1. Use gomodinit to initialize the module, such as gomodinitexample.com/myproject; 2. Place the local package in a subdirectory, such as mypkg/utils.go, and the package is declared as packagemypkg; 3. Import it in main.go through the full module path, such as import "example.com/myproject/mypkg"; 4. Avoid relative import, path mismatch or naming conflicts; 5. Use replace directive for packages outside the module. Just make sure the module is initialized

AruneinGoisaUnicodecodepointrepresentedasanint32,usedtocorrectlyhandleinternationalcharacters;1.Userunesinsteadofbytestoavoidsplittingmulti-byteUnicodecharacters;2.Loopoverstringswithrangetogetrunes,notbytes;3.Convertastringto[]runetosafelymanipulate
