360 Secure SkillHub
360 安全技能中心

Race Condition

面向并发编程的竞态条件知识说明:列举计数器丢失更新、检查后执行重复创建、共享缓存被无锁修改、仅高负载下复现的数据损坏等典型症状,并建议用原子操作、不可变数据或消息传递替代共享可变状态,加锁时尽量缩短持锁时间,并显式进行并发压力测试。

分类:开发
mvogt99
mvogt99
热度 25.69
最近更新 2026-05-11 17:46:01

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add mvogt99/race-condition
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
race-condition
description
Shared mutable state is accessed from concurrent contexts without synchronization, producing nondeterministic behavior.
emoji
🏁
metadata
{"clawdis":{"os":["macos","linux","windows"]}}

race-condition

Two or more concurrent contexts — threads, async tasks, processes, requests — read and write the same state without coordination. Tests pass on a lightly-loaded machine; production corruption appears under real traffic.

Symptoms

  • Counters that "mostly" work but occasionally lose increments.
  • Check-then-act sequences (e.g., "if not exists, create") where two contexts both pass the check and both create.
  • Shared caches or singletons mutated from request handlers without a lock.
  • Data-corruption bugs that only reproduce under load or with specific timing.

What to do

  • Identify every piece of shared mutable state. Draw the boundary: who reads it, who writes it, from which contexts.
  • Replace check-then-act with atomic operations: compare-and-swap, INSERT ... ON CONFLICT, unique indexes, setnx.
  • Prefer immutable data or message-passing over shared mutation. Actor-style patterns remove most races by construction.
  • When a lock is unavoidable, hold it for the shortest possible span and document what state it protects.
  • Test concurrency explicitly. A single-threaded test proves nothing about a multi-threaded code path. Use stress tests or pytest-asyncio / concurrent harnesses.