批量多進程創建
錯誤方式:
創建第一個線程時,該線程來不及保存namebuffer的數據就切換到主線程
然后主線程修改namebuffer準備創建第二個線程,而導致前一個線程還未
保存的數據被第二個線程的數據所覆蓋了,導致最后輸出多個線程的內容一樣
且有部分線程輸出內容缺失
#include<iostream>
#include<unistd.h>
#include<cassert>
#include<vector>
#include<pthread.h>
using namespace std;
//新線程,函數被多個線程調用:重入狀態
void *thread_routine(void *args){
string name = static_cast<const char*>(args);
while(true){
cout<<"my name is "<<name<<endl;
sleep(1);
}
return nullptr;
//pthread_exit(nullptr);
}
int main(){
//1.創建一批線程
vector<pthread_t> tids;
#define NUM 10
for(int i=0;i<NUM;i++){
pthread_t tid;
char namebuffer[64];
snprintf(namebuffer,sizeof(namebuffer),"chile thread [%d]",i);
pthread_create(&tid,nullptr,thread_routine,(void*)namebuffer);
tids.push_back(tid);
}
while(true){
// cout<<"main thread is running"<<endl;
sleep(5);
}
return 0;
}
解決方案
用一個類保存所有數據,然后傳指針,當主線程創建新的線程時,因為new出來的是一個新指針,
所以對該指針的指向內容修改并不會影響前一個子進程的內容
#include<iostream>
#include<unistd.h>
#include<cassert>
#include<vector>
#include<pthread.h>
using namespace std;
class ThreadData{
public:
pthread_t tid;
char namebuffer[64];
};
void *func_2(void *args){
ThreadData *td=static_cast<ThreadData*>(args);
int cnt=100;
while(cnt--){
cout<<"my name is "<<td->namebuffer<<endl;
sleep(1);
}
delete td;
return nullptr;
//pthread_exit(nullptr);
}
int main(){
vector<pthread_t> tids;
#define NUM 10
for(int i=0;i<NUM;i++){
ThreadData *td=new ThreadData;
snprintf(td->namebuffer,sizeof(td->namebuffer),"chile thread [%d]",i);
pthread_create(&(td->tid),nullptr,func_2,(void*)td);
tids.push_back(td->tid);
}
//waiting thread quit
for(int i=0;i<(int)tids.size();i++){
//阻塞式等待
pthread_join(tids[i],nullptr);
}
cout<<"all thread quit successfully"<<endl;
while(true){
sleep(5);
}
return 0;
}

浙公網安備 33010602011771號