关于向线程的运行函数传递一个参数和多个参数

1.线程创建

#include <pthread.h>
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号

参数说明:
第一个参数为指向线程标识符的指针。
  第二个参数用来设置线程属性。
  第三个参数是线程运行函数的起始地址。
  最后一个参数是运行函数的参数。
  另外,在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库

2.向运行函数只传递一个参数时:直接定义一个变量,将该变量的地址作为arg参数传入。

#include<stdio.h>
#include <pthread.h>
 // int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
void *func(void *arg)
{
    
    
        static char *ret="lanlan!!!";

        printf("t1: param=%d\n",*((int *)arg));
        printf("t1: func's id =%ld\n",(unsigned long)pthread_self());

        pthread_exit((void *)ret);
}

int main()
{
    
    
        pthread_t t1;
        int param = 10; //只传递一个参数
        char *pret = NULL;
        int ret = pthread_create(&t1,NULL,func,(void *)&param);//注意取地址符号
        
        if(ret == 0){
    
    
                printf("main:  pthread_create success\n");
                printf("main:  id=%ld\n",(unsigned long)pthread_self());
        }
        pthread_join(t1,(void **)&pret);

        printf("main: return data=%s\n",pret);
        return 0;
}

2.向执行函数传递多个参数时:如果需要向执行函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg参数传入。

#include<stdio.h>
#include <pthread.h>
#include<string.h>
#include<stdlib.h>

 // int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);

struct text
{
    
    
        int a;
        char b;
        char c[128];
        char *d;
};

void *func(void *arg)
{
    
    
        static char *ret="lanlan!!!";

        struct text *arg1 = (struct text *)arg;//!!!!!!!!!!!!!

        printf("t1: a=%d\n",arg1->a);
        printf("t1: b=%c\n",arg1->b);
        printf("t1; c=%s\n",arg1->c);
        printf("t1: d=%s\n",arg1->d);

        printf("t1: func's id =%ld\n",(unsigned long)pthread_self());

        pthread_exit((void *)ret);
}


int main()
{
    
    
        pthread_t t1;
        char *pret = NULL;
      
//      struct text param = {1056,'L',"SADSDAD","dada"};
        struct text param = {
    
    1056,'L'};
        memset(param.c,0,sizeof(param.c));
        strcpy(param.c,"SADSDAD");
        
        param.d = (char *)malloc(128);
        strcpy(param.d,"dada");
        
        int ret = pthread_create(&t1,NULL,func,(void *)&param);

        if(ret == 0){
    
    
                printf("main:  pthread_create success\n");
                printf("main:  id=%ld\n",(unsigned long)pthread_self());
        }

        pthread_join(t1,(void **)&pret);
        printf("main: return data=%s\n",pret);
        free(param.d);//malloc堆区的内存释放,防止内存泄漏
        return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_46777053/article/details/111317239