[英]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.