我正在尝试将用户级线程库实现为项目的一部分。我的重点是连接功能。让我们说Thread1调用Thread2上的join函数。我需要做的是从Thread2获取提供给pthread_exit()的返回值/参数,并将其存储在join function参数中指定的内存位置。
但是,我如何获得另一个线程的返回值?
任何帮助将不胜感激。感谢
答案 0 :(得分:3)
以下是GnuPth(pth_lib.c
)用户级线程库的示例,该库分别显示了exit
和join
函数的实现。我简化代码以突出显示返回值处理。
void pth_exit(void *value)
{
pth_debug2("pth_exit: marking thread \"%s\" as dead", pth_current->name);
/* the main thread is special, because its termination
would terminate the whole process, so we have to delay
its termination until it is really the last thread */
/* execute cleanups */
/*
* Now mark the current thread as dead, explicitly switch into the
* scheduler and let it reap the current thread structure; we can't
* free it here, or we'd be running on a stack which malloc() regards
* as free memory, which would be a somewhat perilous situation.
*/
pth_current->join_arg = value;
pth_current->state = PTH_STATE_DEAD;
pth_debug2("pth_exit: switching from thread \"%s\" to scheduler", pth_current->name);
//return (for ever) to the scheduler
}
和相应的pth_join
:
/* waits for the termination of the specified thread */
int pth_join(pth_t tid, void **value)
{
//Validate thread situation.
//wait until thread death
//save returned value for the caller
if (value != NULL)
*value = tid->join_arg;
//remove thread from the thread queue
//free its memory space
return TRUE;
}
答案 1 :(得分:2)
您可以为应用程序或进程上下文中的返回值创建存储,并在线程库初始化时初始化。你的pthread_exit将填充该值,你的连接将使用threadid来检索它 - 我认为这只适用于非动态分配的返回值。
答案 2 :(得分:1)
我对你实现中个别线程的元信息感兴趣。除了ID,堆栈指针等之外,返回值可以是存储在线程中的项之一。
调用pthread_exit()时,调度程序应将此类信息转储到一个或多个数据结构中,以便其他线程可以在需要时查询它们。