线程和指针数组?

时间:2014-04-09 07:15:53

标签: c++ arrays multithreading pointers dynamic-arrays

下面的代码有问题,在线程完成工作后,数组的输出是一个狂热的数据,而它没有线程正常工作,任何人都可以帮助我解释原因!!!!!

#include<iostream>
#include <thread> 

using namespace std;


class Case1{

public:
 int *pplAges[5];
 Case1(){
 *pplAges= new int[5];
 }

 void addToAges(int Age, int index){
 pplAges[index] = new int;
 *pplAges[index] = Age;
 cout<< *pplAges[index] <<endl;

 }


};

void f1(Case1 passedObj,int age,int index)
{

passedObj.addToAges(age,index);

}

void main(){

 Case1 C;

thread t1(f1,C,13,0);
t1.join();

thread t2(f1,C,14,2);
t2.join();

cout<<*C.pplAges[0]<<endl;
cout<<*C.pplAges[2]<<endl;
}

2 个答案:

答案 0 :(得分:2)

线程复制其参数,因此您的线程永远不会更改C。如果你想明确地引用一个引用,你必须用std :: ref(或者std :: cref用于常量引用)来包装它:

void f1(Case1& passedObj, int age, int index)
{

    passedObj.addToAges(age, index);

}

void main(){

    Case1 C;

    thread t1(f1, std::ref(C), 13, 0);
    t1.join();

    thread t2(f1, std::ref(C), 14, 2);
    t2.join();



    cout << *C.pplAges[0] << endl;
    cout << *C.pplAges[2] << endl;
}

答案 1 :(得分:1)

尝试改变

void f1(Case1 passedObj,int age,int index)

void f1(Case1* passedObj,int age,int index)

并传递线程&C