创建多个线程并传参数时,如果传入的参数是个局部变量,最好new内存然后在thread中释放内存,否则这块内存容易被覆盖而导致thread中用的数据发生变化。示例如下:
struct mac_data{
string mac;
string account;
string password;
string status;
};
void function1()
{
vector<mac_data> macs = vector<mac_data>();
/*
code to add items to macs;
*/
for (unsigned int i = 0;i < macs.size();i++)
{
struct mac_data *m = new mac_data();
m->status = macs[i].status;
cout<<"begin to setup machine "<<i <<" "<<m->mac<<". current status is "<<m->status<<endl;
if(m->status !=MACREADY && m->status !=MACBUSY)//1 means ready, 2 means running cases
{
m->mac = macs[i].mac;
m->account = macs[i].account;
m->password = macs[i].password;
rc = pthread_create(&preThreads[i],&attr,prepareEnv,(void *)m);
if(rc)
{
cout<<"pthread_create error code "<<rc<<endl;
}
}
}
}
void *prepareEnv(void *threadarg)
{
int status =0;
if(1 >0)
{
struct mac_data *t;
t = (struct mac_data *) threadarg;
struct mac_data m;
m.mac = t->mac;
m.password = t->password;
m.account = t->account;
delete t;
}
return NULL;
}