pthread创建多线程

 

 

#include <iostream>

#include <pthread.h>

#include <string.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <dirent.h>

#include <errno.h>

#include <vector>

#include <algorithm>

#include <unistd.h>

#include "tinyxml/tinyxml.h"

#include <stdexcept>

#include <map>

#include <fcntl.h>

#include <stdlib.h>

#define MACXML "mac.xml"

using namespace std;

 

static bool usingMacXml = false;

pthread_mutex_t mutexMac = PTHREAD_MUTEX_INITIALIZER;

 

struct mac_data{

    string mac;

    string account;

    string password;

    string status;

};

 

/// run cmd command

int RunMsg(string cmd)

{

    int rc = system(cmd.c_str());

    if(!rc)

        printf("excute %s, result is %d/n",cmd.c_str(), rc);

    printf("Cmd: %s, result is %d/n",cmd.c_str(), rc);

    return rc;

}

 

///prepare environment:copy all ci content except case;run cienv_setup.sh to setup environment;"

void *prepareEnv(void *threadarg)

{

    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;

 

    string mac = m.account+string("@") +m.mac;

    string password = m.password;

    string preMsg = "./execute "+mac+" "+ password+" /"if [ -d ~/dd];then/nrm ~/dd -rf;/nfi;/"";

    RunMsg(preMsg);

    preMsg ="./pscp "+password+" ~/dd "+mac+":~";

    RunMsg(preMsg);

    preMsg ="./execute "+mac+" "+ password+" /"cd ~/dd/shell;sh ./ddenv_setup.sh;source ~/.bash_profile;/"";

    RunMsg(preMsg);

}

 

 

/// 多线程配置环境

void setupEnvInMultiThread(vector<mac_data> macs)

{

    int tCount = macs.size();

 

    pthread_t preThreads[tCount];

    pthread_attr_t attr;

 

    pthread_attr_init(&attr);

    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);

 

    int rc;

 

    for (unsigned int i = 0;i < macs.size();i++) 

    {

        struct mac_data m = macs[i];

        cout<<"machine "<<i <<" "<<m.mac<<endl;

        rc = pthread_create(&preThreads[i],&attr,prepareEnv,(void *)&m);

        system("sleep 3");

        if(rc)

        {

            cout<<"pthread_create error code "<<rc<<endl;

        }

    }

    pthread_attr_destroy(&attr);

 

    void * status;

    for(int j=0;j<tCount;j++)

    {

        rc = pthread_join(preThreads[j],&status);

        if(rc)

        {

            cout<<"pthread_join error code "<<rc<<endl;

        }

        cout<<"Main: completed join with thread "<<j<<" having a status of "<<status<<endl;

    }

 

    cout<<"prepare environment completed."<<endl;

 

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值