You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

线程独立变量存储类选择及thread_local同一线程多调用副本诉求

Answers to Your Thread Storage Questions

1. Storage Class for Per-Thread Variable Copies

If you need a variable that has an independent instance in every thread, the right choice is the thread_local storage specifier (added in C11). For older compilers that don’t support C11, you might encounter the non-standard __thread extension (common in GCC) which serves the same purpose.

Variables marked thread_local are initialized once per thread, and they stick around for the entire lifetime of that thread. Each thread gets its own separate copy, so modifications in one thread won’t affect the variable’s value in any other thread.


2. Getting Fresh Copies on Every Function Call (Same Thread Included)

The behavior you’re seeing with thread_local is exactly how it’s intended to work: it keeps the variable’s value intact across multiple calls to your call_mult function within the same thread. If you want a brand-new, independent copy of rage every time the function runs—even when the same thread calls it twice in a row—thread_local isn’t what you need here.

Instead, just declare rage as a standard local variable inside call_mult:

void call_mult() {
    int rage = 0; // A new instance is created every time this function is called
    // ... your code using rage ...
}

Regular local variables live in the thread’s stack. Every time the function is invoked—whether by the same thread or a different one—a new instance of rage is created in the current call’s stack frame, and it’s destroyed when the function returns. This guarantees that every call to call_mult gets its own isolated rage variable, no matter which thread is executing it.

Just to clarify: if your original goal was to prevent cross-thread sharing, regular local variables already handle this automatically. Each thread has its own stack, so variables from one thread’s function calls never interfere with those from another. thread_local is only useful when you want a variable to retain its state across multiple function calls in the same thread (like a thread-specific counter that persists between calls), while still being separate from other threads.


内容的提问来源于stack exchange,提问作者Tushar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:27:02