[英]Does a static object within a function introduce a potential race condition?
I'm curious about the following code: 我对以下代码感到好奇:
class MyClass
{
public:
MyClass() : _myArray(new int[1024]) {}
~MyClass() {delete [] _myArray;}
private:
int * _myArray;
};
// This function may be called by different threads in an unsynchronized manner
void MyFunction()
{
static const MyClass _myClassObject;
[...]
}
Is there a possible race condition in the above code? 上面的代码中是否存在可能的竞争条件? Specifically, is the compiler likely to generate code equivalent to the following, "behind the scenes"? 具体地说,编译器是否有可能生成与“幕后”相同的代码?
void MyFunction()
{
static bool _myClassObjectInitialized = false;
if (_myClassObjectInitialized == false)
{
_myClassObjectInitialized = true;
_myClassObject.MyClass(); // call constructor to set up object
}
[...]
}
... in which case, if two threads were to call MyFunction() nearly-simultaneously, then _myArray might get allocated twice, causing a memory leak? ...在这种情况下,如果两个线程几乎同时调用MyFunction(),那么_myArray可能会分配两次,从而导致内存泄漏?
Or is this handled correctly somehow? 还是以某种方式正确处理了?
There's absolutely a possible race condition there. 那里绝对是可能的比赛条件。 Whether or not there actually is one is pretty damn undefined. 是否真的存在一个是该死的未定义。 You shouldn't use such code in single-threaded scenarios because it's bad design, but it could be the death of your app in multithreaded. 您不应在单线程方案中使用此类代码,因为这是糟糕的设计,但可能会导致您的应用程序在多线程中死亡。 Anything that is static const like that should probably go in a convenient namespace, and get allocated at the start of the application. 任何像静态const这样的东西都应该放在方便的名称空间中,并在应用程序的开始处分配。
如果使用多个线程,请使用信号量,这就是它们的作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.