360 Secure SkillHub
360 安全技能中心

Race Condition

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

mvogt99
mvogt99
热度 33.28
最近更新 2026-05-11 17:46:01
分类:开发依赖:纯提示词应用场景:调试排错 / 概念解释

安装技能

复制下面的话术发给你的 Agent,它会通过 secure-skills 检索并安装该技能。

执行命令安装此 skill: npx secure-skills-cli add 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.