问题描述
在c ++中,我们可以有实例方法和类方法.
假设我有一个名为A的类
In c++, we can have instance methods and class methods.
Suppose I have a class named A
class A
{
...
void inst_method() { ... }
static void static_method() { .. }
}
还要假设我有两个类A的实例:
A a1,a2;
我的问题是在运行时
1. a1和a2对inst_method的代码有自己的对应吗?如果不是,是否有可能其他线程更改inst_method中的局部变量?
2.如果a1和a2在两个独立的线程中,那么static_method是否可以同时运行?多CPU和单CPU的情况如何?如果是这样,则static_method中的局部变量是否会被另一个线程更改?
假设这是static_method的定义:
Also suppose I have two instances of class A:
A a1, a2;
My question are in the run-time
1. do a1 and a2 have their own copes of the code for inst_method? if not, is it possible that the local variables in inst_method will be changed by other thread?
2. if a1 and a2 are in two independent threads, then is it possible that static_method will be run in the same time? how about the cases of the multi-CPU and the single-CPU? if so, will the local variables in the static_method be changed by the other thread?
Let''s say here is the definition of the static_method:
void static static_method()
{
bool flag = false;
//... a big job
for(int i = 0; i< 10; i++)
{
if( !flag )
{
// a big job
flag=true;//->if another thread changes the flag, then we are in trouble
}
}
}
非常感谢.
Damon
Thanks a lot.
Damon
推荐答案
这篇关于有关方法的线程安全问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!