从一个线程返回参数(struct)

时间:2015-12-28 03:24:07

标签: c multithreading pthreads

我有一个函数task1,由main(纯C)中的pthread_create调用。它可以工作但是,无论我在my_pair上做什么都会在线程结束后丢失。我的意思是我希望创建的线程task1执行操作并将它们保存在eventT上..是否可以返回my_pair?如何?

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 );

1 个答案:

答案 0 :(得分:1)

这是一个从线程返回结构的方法的示例 - 通过传入一个分配的结构来返回线程。此示例与您发布的代码类似,但仅使用pthread个函数,因为我对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;
}

这可以做的另一种方法是让线程分配返回的结构而不是调用者并将其传入。我确定有很多其他机制可以使用,但是这应该可以帮到你启动。