批量多进程创建

错误方式:

创建第一个线程时,该线程来不及保存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;
}
posted @ 2025-11-01 11:26  xdhking  阅读(7)  评论(0)    收藏  举报