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

请问使用全局变量DNMTemp的DNMManager_New函数是否可重入?

Is DNMManager_New a Reentrant Function?

Let’s break this down clearly, starting with the code you’ve shared:

// Global variable definition
struct DNM_s { 
    uint32_t Addr; 
    uint32_t SerialNum; 
    uint32_t SubnetMask; 
    uint16_t Tick; 
    uint8_t Name[NAME_SIZE]; 
} DNMTemp;

// Function implementation
pDNM DNMManager_New(void) { 
    return &DNMTemp; 
}

First, let’s ground ourselves in what makes a function reentrant: A reentrant function can be safely interrupted mid-execution and called again (either recursively or by another thread) without causing undefined behavior or inconsistent state. The key guardrail here is that reentrant functions shouldn’t rely on or modify mutable global/static data in a way that creates race conditions.

Now, looking at DNMManager_New:

  • It only returns the memory address of the global DNMTemp variable. It never modifies DNMTemp’s value, and its execution has zero side effects.
  • Every call to this function returns the exact same pointer—there’s no state that changes between calls, no computation that depends on shared data, and no risk of interleaved execution causing unexpected results.

The common guideline that "reentrant functions shouldn’t use global data" is a safe best practice to avoid accidental bugs (like if you later modify the function to write to DNMTemp), but it’s not the strict definition of reentrancy. The strict test is: does the function’s own behavior break when called concurrently or recursively?

In this case, the answer is no. Even if two threads call DNMManager_New at the same time, or if the function is called recursively, every invocation will return the same address, and there’s no undefined behavior introduced by the function itself.

A critical caveat: The code that uses the pointer returned by DNMManager_New might not be reentrant if it modifies DNMTemp without proper synchronization. But that’s a separate issue—the DNMManager_New function itself is reentrant.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:02:42