4.线程参数传递<3>

38 阅读1分钟
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <string.h>
using namespace std;

/*线程参数传递
    1.创建的多个线程并不保证哪个线程先运行
    2.不能用全局变量代替线程函数的参数
    3.数据类型的强制转换

*/

//如果要给线程传入多个参数,定义一个结构体,把需要传入的内容定义到结构体中。
struct st_args
{
    int no;     //线程编号
    char name[51];  //线程名字

};

void *thmain1(void *arg);
void *thmain2(void *arg);

int main(int argc, char *argv[])
{
    pthread_t thid1=0, thid2=0;

    //创建线程 给每一个线程传参数,如果传相同的地址是不行的, 传不同的地址OK
    struct st_args* st1 = new(struct st_args);
    st1->no = 1;
    strcpy(st1->name,"thread1");
    if(pthread_create(&thid1, NULL, thmain1, st1) != 0) {printf("thid1 faile\n");}
    
    struct st_args* st2 = new(struct st_args);
    st2->no = 2;
    strcpy(st2->name,"thread2");
    if(pthread_create(&thid2, NULL, thmain2, st2) != 0) {printf("thid2 faile\n");}

    
    //等待子线程退出
    cout << "thmain start..." << endl;
    pthread_join(thid1, NULL);          //主线程等待子线程退出
    pthread_join(thid2, NULL);
    cout << "thmain end " << endl;
    return 0;
}


void *thmain1( void *arg)
{
    struct st_args* pst = (struct st_args*)arg;
    printf("thmain1 no = %d, name = %s\n", ((struct st_args*)arg)->no, ((struct st_args*)arg)->name);  
    delete pst;      //释放内存
    printf("thmain1 start...\n");
}

void *thmain2( void *arg)
{
    struct st_args* pst = (struct st_args*)arg;
    printf("thmain2 no = %d, name = %s\n", pst->no, pst->name);
    delete pst;      //释放内存
    printf("thmain2 start...\n");
}