簡體   English   中英

從線程返回參數(結構)

[英]return argument (struct) from a thread

我有一個函數task1,該函數由主線程(純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 );

這是從線程返回結構的一種方法的示例-通過傳入分配的結構以使線程返回。 此示例與您發布的代碼類似,但是僅使用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;
}

可以完成此操作的另一種方法是讓返回的結構由線程分配,而不是由調用者分配,然后將其傳遞。我確定可以使用許多其他機制,但這應該可以幫助您入門。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM