Consider this code:
class info{
public:
char name[10];
int age;
float money;
info(char nam[10], int ag, float mon):age(ag),money(mon){
strcpy(name,nam);
}
info():age(0),money(0){
strcpy(name,"");
}
};
void *foo(void* data){
info *args;
args=static_cast<info*>(data);
cout<<"\nName: "<<args->name<<endl;
cout.flush();
cout<<"Age: "<<args->age<<endl;
cout.flush();
cout<<"Balance: "<<args->money<<endl;
cout.flush();
pthread_exit(NULL);
}
int main(){
int x;
cout<<"Enter number of accounts: ";
cin>>x;
info *A[x]; /*MARKED LINE*/
pthread_t t[x];
int rc;
for(int i=0;i<x; i++){
A[i]=new info();
cout<<"\nEnter name: ";
cin>>A[i]->name;
cout<<"Enter age: ";
cin>>A[i]->age;
cout<<"Enter Balance: ";
cin>>A[i]->money;
}
for(int i=0; i<x; i++){
rc=pthread_create(&t[i],NULL,foo,static_cast<void*>(A[i]));
if(rc!=0){
cout<<"Unable to create thread";
exit(-1);
}
}
pthread_exit(NULL);
}
The output of this code is the random cout
as expected from multithreaded program. But when I change the MARKED LINE
from
info *A[x];
to info *A[x]={0}
,
I get the cout
in the sequential manner that I entered them, Like If I entered A, B, and C, then the output will also be the same, and not in the random manner. I want to know why this happened.