简体   繁体   English

cpp主体线程本地的函数安全吗? 如果是这样,从中调用静态函数呢?

[英]Are functions local to a cpp body thread safe? If so what about calling static functions from it?

I have a lot of multithreading bugs since I introduced a second worker thread. 自从引入第二个工作线程以来,我遇到了很多多线程错误。 The issues are minor and hard to trace. 这些问题很小,很难追踪。 My latest indications point to 我的最新迹象表明

class MyOtherClass {
    static String defaultName;
    static String getDefaultName() {return defaultName;}
}

which is being used by: 由以下人员使用:

result plainLocalFunction() {
    result r = E_SUCCESS;
    String fallbackName = MyOtherClass::getDefaultName();
    //Do other stuff with locals.
    return r;
}

I've been ages debugging this and I can only suppose that either the plainLocalFunction is shares its locals between threads or that that the call to getDefaultName() involves writing to a static variable which is not thread safe? 我已经调试了很久了,我只能假设plainLocalFunction是在线程之间共享其plainLocalFunction变量,或者对getDefaultName()的调用涉及写入不是线程安全的静态变量? Thanks for your time. 谢谢你的时间。

static variables inside a function would render your function not re-entrant and not thread safe. 函数内的静态变量会使您的函数无法重入并且也不是线程安全的。

If you have just local variables in a function then each thread stack will have its own copy of those variables and the function will be thread safe. 如果函数中只有局部变量,则每个线程堆栈将拥有自己的那些变量副本,并且该函数将是线程安全的。

Static variables are absolutely not thread safe if you write to them (here: defaultName). 如果您对静态变量进行写操作,则它们绝对不是线程安全的(此处为defaultName)。 Reading (if Nobody writes to it) should be okay though and I don't think calling a static function (or a dynamic one for what matters) is thread-unsafe if there are no thread-unsafe things going on in it. 读取(如果没有人写的话)应该可以,而且我不认为如果其中没有发生线程不安全的事情,则调用静态函数(或动态的函数)不会导致线程不安全。

Use CriticalSections (for example) to protect your variables that are used by several threads (and at least one thread might write to it). 使用CriticalSections (例如)来保护由多个线程使用的变量(并且可能至少有一个线程可以写入该变量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM