pthread_create传递多个参数

一、传递一个参数。

image

 

#include <iostream>
#include <pthread.h>
using namespace std;

void* thr_fn(void* arg)
{
        int i = *(int*)arg;
        cout << i << endl;

        return ((void*)0);
}

int main()
{
        pthread_t tid;

        int j = 2;

        pthread_create(&tid, NULL, thr_fn, &j);

        sleep(2);
        return 0;
}

二、传递多个参数。

#include <iostream>
#include <pthread.h>
using namespace std;

struct parameter
{
        char a;
        int i;
        float f;
};

void* thr_fn(void* arg)
{
        struct parameter *p =(parameter*)arg;

        cout << p->a << endl;
        cout << p->i << endl;
        cout << p->f << endl;

        return ((void*)0);
}

int main()
{
        pthread_t tid;

        struct parameter *par =  new parameter;
        par->a = 'c';
        par->i = 2;
        par->f = 3.14;

        pthread_create(&tid, NULL, thr_fn, (void*)par);

        sleep(2);
        return 0;
}

原文地址:https://www.cnblogs.com/helloweworld/p/3509773.html