简体   繁体   中英

return argument (struct) from a thread

I have a function task1 that is called by the pthread_create in the main (pure C). It works but, whatever I do on my_pair is lost after the thread is over. I mean I would like the created thread task1 do operations and save them on eventT.. is it possible to return my_pair? how?

void task1(void* eventT){
    //struct eventStruct *my_pair = (struct eventStruct*)eventT;
    // Tried with malloc but same wrong behavior
    struct eventStruct *my_pair = malloc(sizeof((struct eventStruct*)eventT));

    // do stuff
    my_pair->text = TRIAL;
    pthread_exit( my_pair );

}

// Global variable
struct eventStruct *eventT = NULL;


//Calling the thread from the main
eventT = (struct eventStruct*)
thpool_add_work(thpool, (void*)task1, (void*) &eventT);

// Expecting eventT changed (not happening..)
pthread_join( thread, &eventT );

Here's an example of one way to return a struct from a thread - by passing in an allocted struct for the thread to return. This example is similar to your posted code, but uses only pthread functions since I don't know anything about the thpool_add_work() API.

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


struct eventStruct
{
    char const* text;
    char const* more_text;
};

#define TRIAL "this is a test"

void* task1(void* eventT)
{
    struct eventStruct *my_pair = (struct eventStruct*)eventT;

    // do stuff

    my_pair->text = TRIAL;
    pthread_exit( my_pair );
}


int main(void)
{
    pthread_t thread;


    struct eventStruct* thread_arg = malloc(sizeof *thread_arg);

    thread_arg->text = "text initialized";
    thread_arg->more_text = "more_text_initialized";

    //Calling the thread from the main
    pthread_create( &thread, NULL, task1, thread_arg);

    void* thread_result;
    pthread_join( thread, &thread_result);

    struct eventStruct* eventT = thread_result;
    puts(eventT->text);
    puts(eventT->more_text);

    free(eventT);

    return 0;
}

Another way this could be done is by having the returned structure allocated by the thread instead of by the caller and passing it in. I'm sure there are many other mechanisms that can be used, but this should get you started.

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