2.线程参数传递<1>

114 阅读2分钟

线程参数的传递(奇巧淫技)

创建的多个线程并不保证哪个线程先运行
不能用全局变量代替线程函数的参数
数据类型的强制转换
    1.如何传递整形参数
    2.如何传递地址参数(要传多个参数的时候只能传地址了)
    3.线程退出状态(pthread_join第二个参数可以得到线程退出的状态或返回值)
    
    
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std;

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

void *thmain1(void *arg);
void *thmain2(void *arg);
void *thmain3(void *arg);
void *thmain4(void *arg);
void *thmain5(void *arg);

int var = 0;

int main(int argc, char *argv[])
{
/*
    3.数据类型的强制转换
    int i = 10;
    void *pv = 0;   //指针占内存8字节,用于存放变量的地址
    //pv = i;   //错误:从类型‘int’到类型‘void*’的转换无效
    //pv = (void *)i; //警告:将一个整数转换为大小不同的指针
    pv = (void *)(long)i;   //编译通过pv = 0xa, 先把i转换为long,再转为void*
    printf("pv = %p\n", pv);


    int j = 0;
    //j = pv; //错误:从类型‘void*’到类型‘int’的转换无效
    //j = (int)pv;    //错误:从‘void*’到‘int’的转换损失精度
    j = (int)(long)pv;  //先将pv存放的内容转为long, 再转为int
    printf("j = %d\n", j);  //j = 10
    return 0;
*/

    pthread_t thid1=0, thid2=0, thid3=0;
    pthread_t thid4=0, thid5=0;

    //创建线程 //把这个值传进去不能传变量的地址。进行两个类型转换。
    var = 1;
    if(pthread_create(&thid1, NULL, thmain1, (void *)(long)var) != 0) {printf("thid1 faile\n");}
    var = 2;
    if(pthread_create(&thid2, NULL, thmain2, (void *)(long)var) != 0) {printf("thid2 faile\n");}

    var = 3;
    if(pthread_create(&thid3, NULL, thmain3, (void *)(long)var) != 0) {printf("thid3 faile\n");}
  
    var = 4;
    if(pthread_create(&thid4, NULL, thmain4, (void *)(long)var) != 0) {printf("thid4 faile\n");}

    var = 5;
    if(pthread_create(&thid5, NULL, thmain5, (void *)(long)var) != 0) {printf("thid5 faile\n");}
    
    //等待子线程退出
    cout << "thmain start..." << endl;
    pthread_join(thid1, NULL);          //主线程等待子线程退出
    pthread_join(thid2, NULL);
    pthread_join(thid3, NULL);
    pthread_join(thid4, NULL);
    pthread_join(thid5, NULL);
    cout << "thmain end " << endl;
    return 0;
}


void *thmain1( void *arg)
{
    printf("var1 = %d\n", (int)(long)arg);
    printf("thmain1 start...\n");
}

void *thmain2( void *arg)
{
    printf("var2 = %d\n", (int)(long)arg);
    printf("thmain2 start...\n");
}

void *thmain3( void *arg)
{
    printf("var3 = %d\n", (int)(long)arg);
    printf("thmain3 start...\n");
}

void *thmain4( void *arg)
{
    printf("var4 = %d\n", (int)(long)arg);
    printf("thmain4 start...\n");
}

void *thmain5( void *arg)
{
    printf("var5 = %d\n", (int)(long)arg);
    printf("thmain5 start...\n");
}