简体   繁体   中英

Converting from void* to int, in 64 bits Ubuntu, using pthread

my problem is that i need to run a pthread so i can listen a pipe, the thing is i have the pipes in a struc:

struct Pipefd {
    int tuberia1[2];
    int tuberia2[2];
};

this is the way i create the pthread:

intptr_t prueba = pf.tuberia2[0];
pthread_create(NULL,NULL, listenProcess,reinterpret_cast<void*>(prueba));

and here is the method i invoke:

void *listenProcess(void* x){

    int a = reinterpret_cast<intptr_t>(x);
    close(0);
    dup(a);

    string word;

    while(getline(cin,word)){

        cout << "Termino y llego: " << word << endl;

    }
}

it compile, but i get a segmentation fault, but i dont understand. im newby in c++, i already search alot and didnt found an answer to work, the "reinterpret_cast" is a workaround that i found to compile it without errors.

Thanks for your time, im sorry about my english, it is not my mother language, so any grammar error you point, its well recive.

The POSIX threads API allows you to pass a generic void* for user data when your thread function is first called.

Since you already have the following structure defined:

struct Pipefd {
    int tuberia1[2];
    int tuberia2[2];
};

Rather than casting a single field of this structure to void* you might want to pass a pointer to the actual structure:

void* ppf = reinterpret_cast<void *>(&pf);
pthread_create(NULL,NULL, listenProcess,ppf);

Now, your modified thread function would look like this:

void *listenProcess(void* x){
    Pipefd* ppf = reinterpret_cast<Pipefd *>(x);
    close(0);

    dup(ppf->tuberia2 [0]);

    string word;

    while(getline(cin,word)){
        cout << "Termino y llego: " << word << endl;
    }
}

UPDATE:

You also had an invalid call to pthread_create (...) , you must pass it a pointer to a pthread_t variable. This should fix your segmentation fault caused by calling pthread_create (...) :

void*     ppf = reinterpret_cast<void *>(&pf);
pthread_t tid;
pthread_create(&tid,NULL, listenProcess,ppf);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM