简体   繁体   English

从线程返回参数(结构)

[英]return argument (struct) from a thread

I have a function task1 that is called by the pthread_create in the main (pure C). 我有一个函数task1,该函数由主线程(纯C)中的pthread_create调用。 It works but, whatever I do on my_pair is lost after the thread is over. 它可以工作,但是线程结束后,我对my_pair所做的任何操作都会丢失。 I mean I would like the created thread task1 do operations and save them on eventT.. is it possible to return my_pair? 我的意思是我希望创建的线程task1进行操作并将其保存在eventT上。是否可以返回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. 此示例与您发布的代码类似,但是仅使用pthread函数,因为我对thpool_add_work() API thpool_add_work()

#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. 可以完成此操作的另一种方法是让返回的结构由线程分配,而不是由调用者分配,然后将其传递。我确定可以使用许多其他机制,但这应该可以帮助您入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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