cpp 主体线程的本地函数是否安全?如果是这样,从它调用静态函数怎么样?
自从引入第二个工作线程以来,我遇到了很多多线程错误。这些问题都很小,而且很难追踪。我的最新迹象表明
class MyOtherClass {
static String defaultName;
static String getDefaultName() {return defaultName;}
}
它正在被使用:
result plainLocalFunction() {
result r = E_SUCCESS;
String fallbackName = MyOtherClass::getDefaultName();
//Do other stuff with locals.
return r;
}
我已经调试了很多年了,我只能假设 plainLocalFunction
在线程之间共享其局部变量,或者调用 getDefaultName ()
涉及写入非线程安全的静态变量?感谢您抽出时间。
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? Thanks for your time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
函数内的静态变量将使您的函数不可重入且不是线程安全的。
如果函数中只有局部变量,那么每个线程堆栈都将拥有这些变量的自己的副本,并且该函数将是线程安全的。
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.
如果您写入静态变量(此处:defaultName),它们绝对不是线程安全的。
读取(如果没有人写入)应该没问题,而且我不认为调用静态函数(或重要的动态函数)是线程不安全的,如果其中没有发生线程不安全的事情。
使用 CriticalSections (例如)来保护多个线程(并且至少有一个线程)使用的变量线程可能会写入它)。
Static variables are absolutely not thread safe if you write to them (here: 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).