有关方法的线程安全问题 [英] thread-safe questions about methods

查看:114
本文介绍了有关方法的线程安全问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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

推荐答案

any 函数的任何非静态局部变量
将分配在函数调用的堆栈上,

因此,对于任何调用上下文,它们都是受保护的"(唯一的):)
Any non-static local variable of any function
will be allocated on the stack of the function call,

so they are "protected" (unique) for any calling context :)


会为调用的函数的每个实例创建局部变量.它们是完全线程安全的,除非您做一些奇怪的事情,例如跨多个线程对它们进行别名.

另一方面,需要保护您的函数修改的任何静态数据成员,使其免受多重访问,否则您将遇到问题.实际上,这是避免使用静态数据的充分理由.

请注意,我在说的是变量而不是它们所使用的函数.无论您在该实例上操作的函数是成员还是成员,该类的每个实例的代码都将相同静态的.

干杯,

Local variables are created for each instance of the function called. They''re completely thread safe unless you do something strange like aliasing them across multiple threads.

On the other hand any static data members modified by your function need to be guarded against multiple access otherwise you will hit problems. This is actually quite a good reason to avoid using static data.

Note that I''m talking about variables not the functions they''re used in. The code is going to be the same for every instance of your class whether the functions operating on those instance are members or static.

Cheers,

Ash


这篇关于有关方法的线程安全问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆