return 来自线程的参数(结构)

return argument (struct) from a thread

我有一个函数 task1,它由主程序(纯 C)中的 pthread_create 调用。它有效,但是,在线程结束后,我在 my_pair 上所做的一切都会丢失。我的意思是我希望创建的线程 task1 执行操作并将它们保存在 eventT.. 是否可以 return 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 );

这是从线程 return 结构的一种方法的示例 - 通过将线程的分配结构传递给 return。此示例类似于您发布的代码,但仅使用 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;
}

另一种方法是通过线程而不是调用者分配 returned 结构并将其传入。我相信还有许多其他机制可以使用,但这应该可以帮助您入门。