【发布时间】:2015-09-06 20:54:39
【问题描述】:
考虑这段代码:
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);
}
这段代码的输出是随机的cout,正如多线程程序所期望的那样。但是当我从
MARKED LINE
info *A[x]; 到 info *A[x]={0},
我以我输入它们的顺序方式获得cout,就像我输入 A、B 和 C 一样,那么输出也将是相同的,而不是以随机方式。我想知道为什么会这样。
【问题讨论】:
-
这可能是
C和C++ STL,而不是真正的C++。 -
@Zereges:不,C++,虽然 C++ 很糟糕。他使用 C++ 风格
special_cast<target_type>(...)。但是,是的,我仍然同意,这是滥用 STL 的 C,而不是 C++。 -
您的建议应该修改以使其更像 C++?那么原始查询呢?
-
少了
char[],多了std::string和std::vector -
我不相信你。你每个都试了多少次?您的观察偶然发生的概率是多少?
标签: c++ multithreading