惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LINUX DO - 最新话题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
PCI Perspectives
PCI Perspectives
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
H
Heimdal Security Blog
S
Security @ Cisco Blogs
N
News | PayPal Newsroom
J
Java Code Geeks
罗磊的独立博客
Security Archives - TechRepublic
Security Archives - TechRepublic
N
News and Events Feed by Topic
V
V2EX
WordPress大学
WordPress大学
Google Online Security Blog
Google Online Security Blog
N
News and Events Feed by Topic
www.infosecurity-magazine.com
www.infosecurity-magazine.com
月光博客
月光博客
AI
AI
小众软件
小众软件
The GitHub Blog
The GitHub Blog
MongoDB | Blog
MongoDB | Blog
A
Arctic Wolf
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
美团技术团队
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tailwind CSS Blog
S
Schneier on Security
博客园 - 三生石上(FineUI控件)
F
Full Disclosure
B
Blog RSS Feed
Forbes - Security
Forbes - Security
S
SegmentFault 最新的问题
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
人人都是产品经理
人人都是产品经理
云风的 BLOG
云风的 BLOG
Jina AI
Jina AI
Cisco Talos Blog
Cisco Talos Blog
U
Unit 42
Project Zero
Project Zero
H
Hacker News: Front Page
Y
Y Combinator Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
The Cloudflare Blog
大猫的无限游戏
大猫的无限游戏
S
Secure Thoughts
The Hacker News
The Hacker News
Microsoft Azure Blog
Microsoft Azure Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
C++ Crash Pattern S5 — Race‑Condition Crashes: How to Diagnose and Fix Them
Wang - C++ Developer · 2026-06-20 · via DEV Community

Why race‑condition crashes only appear under specific timing, vanish under debugging, and produce different stack traces on every run.

Race‑condition crashes are the first pattern in the series where the failure is not deterministic.

The code is correct, the memory is valid, the backtrace may look reasonable, and the crash may even disappear under debugging — but the program still fails unpredictably.

S5 crashes are timing‑dependent failures caused by two or more threads accessing shared state without proper synchronization.

Unlike S4 (wrong‑thread crashes), S5 failures depend on when things happen, not where they happen.

This article explains how to recognize race‑condition crashes, diagnose them efficiently, and fix the underlying concurrency defects.


1. What Is a Race‑Condition Crash?

A race‑condition crash occurs when:

  • multiple threads access shared state
  • at least one access is a write
  • the accesses are not synchronized
  • the outcome depends on timing

The crash is not tied to a specific line of code.

It is tied to interleavings — the order in which threads execute.

S5 crashes are timing failures: the code is correct in isolation, but incorrect when interleavings change.


2. What Race‑Condition Crashes Look Like

Race‑condition crashes have a distinctive signature:

1. Crash location moves
The crash may appear in different functions on different runs.

2. Crash disappears under debugging
Breakpoints, logging, or sanitizers change timing and hide the bug.

3. Crash frequency depends on load
More threads → more failures.
Single‑threaded mode → no failures.

4. Backtrace may look valid or corrupted
Sometimes clean, sometimes garbage — depends on the interleaving.

5. Reproduction is difficult
We may need stress tests, loops, or special timing to trigger it.

6. The crashing line is rarely the root cause
The defect is almost always upstream, in a missing lock or incorrect ownership rule.

Why S5 Nondeterminism Is Different from S2/S3

Race‑condition crashes are nondeterministic because the failure depends on timing, not on corrupted memory.
This is different from S2 and S3: heap and stack corruption also appear nondeterministic, but for a different reason — the program state is already broken, so the crash location moves as corrupted data flows through the system.

In S5, the program is correct in isolation, but incorrect when two threads interleave in the wrong order -- timing matters.
The nondeterminism comes from the scheduler, not from memory corruption.


3. Likely Patterns — Root Causes

Race‑condition crashes come from a small set of mechanisms:

1. Unsynchronized read/write access
One thread writes while another reads.

2. Double‑delete or premature delete
One thread destroys an object while another still uses it.

3. Incorrect use of atomics
Atomics fix visibility, not invariants.
We can still race on multi‑field state.

4. Missing or incorrect locking
Lock not taken, taken too late, or taken in the wrong order.

5. Data structures not designed for concurrency
Vectors, maps, lists, and custom objects are not thread‑safe by default.

6. Races inside callbacks
Callbacks fire on different threads and access shared state.

7. Races in lifetime management
Weak pointer promoted too late, shared pointer destroyed too early.


4. Diagnostic Techniques

Debugging S5 means debugging timing, not memory.

1. Reproduce under stress
Increase thread count, reduce delays, run loops, or use stress harnesses.

2. Use TSAN (Thread Sanitizer)
TSAN is the single most effective tool for detecting data races.

3. Add temporary logging
But be aware: logging changes timing and may hide the bug.

4. Look for shared state
Any object accessed by multiple threads is suspicious.

5. Check lifetime boundaries

  • Who owns the object?
  • Who destroys it?
  • Is destruction synchronized?

6. Examine invariants
Multi‑field invariants require locks, not atomics.

7. Reproduce with forced scheduling
Pin threads, add artificial delays, or use deterministic schedulers.


5. Remediation Steps

Fixing S5 means strengthening synchronization and ownership rules.

1. Add locks around shared state
Mutexes, shared_mutex, or custom guards.

2. Use message‑passing instead of shared state
Push work to the owning thread.

3. Strengthen lifetime management
Use shared_ptr/weak_ptr carefully.
Destroy objects only when no thread can access them.

4. Avoid “lock‑free” unless we truly need it
Lock‑free code is extremely hard to get right.

5. Use atomics only for simple state
Atomics do not protect invariants across multiple fields.

6. Make thread ownership explicit
Document which thread owns which object.


6. Example 1 — Unsynchronized Access to Shared State

A classic race: two threads modify a shared vector.

Code

std::vector<int> data;

void writer() {
    for (int i = 0; i < 1000; ++i) {
        data.push_back(i);
    }
}

void reader() {
    for (int i = 0; i < 1000; ++i) {
        int x = data[i];   // sometimes valid, sometimes crash
    }
}

Symptom

  • Sometimes works
  • Sometimes crashes
  • Sometimes SIGSEGV
  • Sometimes out‑of‑range
  • Sometimes corrupted data

Diagnostic Path

1. Reproduce under stress → inconsistent results → timing issue.
2. Identify shared state → data accessed by two threads.
3. Check for synchronization → none; vector is not thread‑safe.
4. Confirm with TSAN (optional) → write/read race on data.

This leads directly to the root cause: unsynchronized access to a non‑thread‑safe container.

Root Cause

std::vector is not thread‑safe.
Concurrent push_back and read cause reallocation and invalidation.

Fix

std::mutex m;

void writer() {
    std::lock_guard<std::mutex> lock(m);
    data.push_back(...);
}

void reader() {
    std::lock_guard<std::mutex> lock(m);
    int x = data[i];
}


7. Example 2 — Lifetime Race (Use‑After‑Free)

A worker thread uses an object after another thread destroys it.

Code

struct Job {
    void run() { /* ... */ }
};

Job* job = new Job();

void worker() {
    job->run();   // sometimes valid, sometimes UAF
}

void cleanup() {
    delete job;   // races with worker
}

Symptom

  • Crash location moves
  • Sometimes SIGSEGV
  • Sometimes SIGABRT
  • Sometimes no crash

Diagnostic Path

1. Observe nondeterminism → suggests lifetime race.
2. Check ownership → job shared by worker + cleanup.
3. Check destruction timing → delete job may run while worker is active.
4. Force scheduling → adding sleeps changes behavior → confirms timing race.
5.TSAN (optional) → reports race between delete and run

Root Cause

Lifetime is not synchronized.
job is destroyed while worker still uses it.

Fix

Use shared_ptr or explicit synchronization:

std::shared_ptr<Job> job = std::make_shared<Job>();

void worker() {
    auto j = job;   // safe promotion
    if (j) j->run();
}

void cleanup() {
    job.reset();    // safe destruction
}


8. Example 3 — Using TSAN to Diagnose a Race Condition

This example shows a real race condition that does not crash reliably, but TSAN catches immediately.
It demonstrates how to use the tool and how to interpret its output.

Code

#include <thread>
#include <iostream>

int counter = 0;

void worker() {
    for (int i = 0; i < 100000; ++i) {
        counter++;   // unsynchronized write
    }
}

int main() {
    std::thread t1(worker);
    std::thread t2(worker);

    t1.join();
    t2.join();

    std::cout << "counter = " << counter << "\n";
}

This program usually prints something close to 200000, but:

  • sometimes prints a smaller number
  • sometimes prints a corrupted value
  • sometimes crashes
  • sometimes works perfectly

These are classic S5 behavior.

Symptom

  • Nondeterministic output
  • Crash appears only under load
  • Crash disappears when adding logging
  • Crash location moves
  • Debugger hides the bug

This is the signature of a race‑condition crash.

Diagnostic Path

1. Reproduce under stress

Running the program in a loop:

for i in {1..1000}; do ./a.out; done

It produces inconsistent results.

2. Try TSAN

Compile with Thread Sanitizer:

clang++ -fsanitize=thread -g -O1 main.cpp -o tsan_test

Run it:

./tsan_test

3. TSAN immediately reports the race

TSAN output (simplified):

WARNING: ThreadSanitizer: data race
  Write of size 4 at counter by thread T1
    #0 worker main.cpp:7
  Previous write of size 4 at counter by thread T2
    #0 worker main.cpp:7

  Location is global 'counter' at main.cpp:3

TSAN tells us:

  • what is racing (counter)
  • where the race happens (line 7)
  • which threads are involved (T1 and T2)
  • what type of access (write/write)

This is the fastest way to diagnose S5.

Root Cause

counter is shared mutable state accessed by multiple threads without synchronization.

Even though int is small, incrementing it is not atomic:

load → add → store

Two threads interleave these steps unpredictably.

Fix

Use a mutex:

std::mutex m;
int counter = 0;

void worker() {
    for (int i = 0; i < 100000; ++i) {
        std::lock_guard<std::mutex> lock(m);
        counter++;
    }
}

Or use an atomic:

std::atomic<int> counter{0};

void worker() {
    for (int i = 0; i < 100000; ++i) {
        counter.fetch_add(1, std::memory_order_relaxed);
    }
}

After fixing, TSAN reports no races, and the program becomes deterministic.


9. When It’s Not This Pattern

S5 is not the correct pattern when:

  • Crash is deterministic → S1 or S4
  • Backtrace is corrupted → S3
  • Crash location is stable → S1
  • Crash disappears only under sanitizers → S2
  • Crash happens on wrong thread → S4

S5 is specifically about timing‑dependent failures.


10. Summary

  • Race‑condition crashes happen when multiple threads access shared state without proper synchronization.
  • The failure depends on timing, not code correctness.
  • The crash location moves, disappears under debugging, and reappears under load.

The signature is consistent:

  • nondeterministic
  • timing‑dependent
  • moving crash location
  • sometimes clean, sometimes corrupted backtrace
  • disappears under debugging

The only thing wrong is the interleaving.


11. Takeaways

  • S5 is timing‑dependent — the crash depends on interleavings.
  • Crash location moves — the crashing line is rarely the bug.
  • Debugging changes timing — hiding the failure.
  • TSAN is our best friend — use it early.
  • Locks or message‑passing fix most races.
  • Lifetime must be synchronized — destruction races are common.