我正在尝试创建一个线程库,我的线程是一个struct类型.必须遵循某个界面,并且我需要传递threadby值.例如:要加入一个线程,我的代码如下:
int thread_join(thread_t thread, void **status1)
{
printf("Joining thread\n");
long int thId = thread.id;
printf("Thread id: %ld\n", thId);
gtthread_t * thrd = getThreadFromID(thId);
while(thrd->status != EXIT)
{
}
status1 = &(thrd->ret_value);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
而且我将一个struct类型传递给了thread_t这个函数.我的问题是当我在调用函数中看到线程的ID时,它正确显示但是当我在thread_join函数中检查它时显示为0.调用函数如下:
void* caller(void* arg)
{
thread_t th;
thread_create(&th, some_function, NULL);
thread_join(th, NULL);
while(1);
}
Run Code Online (Sandbox Code Playgroud)
线程创建将线程的ID初始化为非零值,并启动与其关联的功能.
我的线程结构(以及其他相关结构):
typedef enum
{
RUNNING,
WAITING,
CANCEL,
EXIT
} stat;
//Thread
typedef struct
{
ucontext_t t_ctxt;
long int id;
stat status;
void * ret_value;
int isMain;
} thread_t;
int thread_create(thread_t *thread, void *(*start_routine)(void *), void *arg)
{
thread = (thread_t *)malloc(sizeof(thread_t));
thread->id = ++count;
thread->status = RUNNING;
thread->ret_value = NULL;
thread->isMain = 0;
if(getcontext(&(thread->t_ctxt)) == -1)
handle_error("getcontext");
thread->t_ctxt.uc_stack.ss_sp = malloc(SIGSTKSZ);
thread->t_ctxt.uc_stack.ss_size = SIGSTKSZ;
thread->t_ctxt.uc_link = &sched_ctxt;
makecontext(&thread->t_ctxt, (void (*)(void))wrap_func, 2, (void (*)(void))start_routine, arg);
enqueue(gQ, thread);
printf("Thread id: %ld\n", thread->id);
swapcontext(&(curr_thread->t_ctxt),&sched_ctxt);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?毕竟,我通过值传递,这应该创建thread具有相同值的副本.谢谢.
编辑:
基本上我有一个线程队列,并有一个循环的调度程序.我也可以在这里发布这些代码,但我确信这是不必要的,而且代码工作正常.
EDIT2:
我正在从这段代码中创建一个头文件,并在另一个文件中包含该头文件来测试它.我的所有thread_t变量都是静态的.调用者是一个包含我的头文件的函数.
这条线是什么:
thread = (thread_t *)malloc(sizeof(thread_t));
Run Code Online (Sandbox Code Playgroud)
对于?
您传入thread_create()一个引用struct thread_t定义caller()为auto变量的地址.
像你一样,你将内存分配给传入的指针以thread_create()初始化它并在返回时忘记地址.
代码永远不会写入传入的地址引用的内存!除此之外,它是内存泄漏.
要解决此问题,只需删除上面引用的代码行.