c++ - 线程间共享类的静态数据

标签 c++ multithreading static-members

在多线程的情况下,是否每个类都共享类的静态成员?例如,一个类具有静态数据成员,如下所示:

class A {
  public:
    static int count;
    ...
};
int A::count(0);

或者,处理方法是每个线程都获得一个单独的静态数据实例,或者每个进程共用?理想情况下,它应该是每个进程一个并在线程之间共享。我有并行运行的 pthreads 访问类静态成员。提前感谢您的意见。

最佳答案

class A{
public:
        static int a;
        A(int count);
        ~A();
        int inc();
        void print();
};
int A::a = 0;
A::A(int count)
{ a = count; }
A::~A()
{ a = -1; }
int A::inc()
{ a=a+1; }
void A::print()
{ cout<<"value:"<<a<<"\n"; }

void *foo(void *p)
{
        class A *aa = new A(0);
        aa->inc();
        aa->print();
        sleep(5);
        cout<<"foo: ";
        aa->print();
        aa->inc();
        cout<<"foo again: ";
        aa->print();
        delete aa;
}
void *boo(void *p)
{
        class A *bb = new A(10);
        bb->inc();
        sleep(1);
        bb->print();
        sleep(2);
        cout<<"boo: ";
        bb->print();
        delete bb;
}

int main()
{
        pthread_t tid,tid2;
        int ret = pthread_create(&tid,NULL,foo,NULL);
        if(ret < 0)
                cout<<"error1";
        ret = pthread_create(&tid2,NULL,boo,NULL);
        if(ret < 0)
                cout<<"error2";
        pthread_join(tid,NULL);
        pthread_join(tid2,NULL);

return 0;
}

下面的输出是

value:1
value:11
boo: value:11
foo: value:-1
foo again: value:0

我认为这澄清了,当然你需要使用同步来避免异常行为。

关于c++ - 线程间共享类的静态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22318767/

相关文章:

python - 从另一个线程调用时未执行的语句

multithreading - Gwt 和 html5 多线程/WebGL 支持

c++ - 为程序全局设置 Linux 上的默认堆栈大小

c++ - 按常量偏移多段线

android - notifyDataSetChanged 不适用于 Thread

c# - 静态字段初始化顺序 (C#) - 有人可以解释这个片段吗?

PHP 可以使用 static::replace self::吗?

c++ - 需要一些关于 r 值概念的帮助

c++ - 什么是对象切片?

c++ - 静态类成员不是与 this 指针没有关联吗?