2011-09-28 44 views
0

我正在尝试将用户级线程库作为项目的一部分来实现。我关注的是连接功能。让我们说Thread1调用Thread2的加入函数。我需要做的是从Thread2中获取提供给pthread_exit()的返回值/参数,并将其存储在join函数参数指定的内存位置中。在用户级线程库中实现连接函数

但是,我如何获得另一个线程的返回值?

任何帮助将不胜感激。谢谢

+0

这完全取决于你的实现是如何工作的。没有通用/便携的方式来执行“用户级线程”。 –

+0

是的,没错。我只是在寻找一个想法来做到这一点。我无法想到这样做。 – CuriousCoder

回答

0

我对你的实现中单个线程的元信息感兴趣。除了ID,堆栈指针等之外,返回值可以是存储在线程中的项目之一。

当调用pthread_exit()时,应该通过调度器将这些信息转储到一个或多个数据结构,以便其他线程可以在需要时查询它们。

+0

我无法将它存储在线程的元信息中,对吗?因为,一旦线程退出,我将不得不释放与线程相关的信息。 – CuriousCoder

+2

不,对于可连接的线程,您不能释放该元信息直到线程连接。否则(1)无处存储返回值,并且(2)相同的线程ID最终可能重新用于新线程。 –

1

您可以在应用程序或进程上下文中为返回值创建存储空间,并在线程库初始化时进行初始化。你的pthread_exit会填充这个值,你的连接将使用threadid来检索它 - 我认为这只会用于非动态分配的返回值。

2

下面是从GnuPthpth_lib.c)用户级线程库,其分别示出了exitjoin和功能的实现,已采取的示例。我简化代码来突出返回值处理。

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; 
} 
+0

感谢您的回复。据我所知,你不会在退出函数中释放与该线程相关的上下文。但是,你什么时候这样做?它可以在连接函数中完成,但如果线程从未由任何其他线程连接,该怎么办?在这种情况下什么时候解脱? – CuriousCoder

+0

是的,Gnupth(不是我!)释放了'join'函数中的线程数据。据我所知(如果我错了,纠正我),除非设置了特定的线程属性,否则POSIX接口强制执行'join'操作。所以你可以在'exit'中添加一个钩子来释放这种特殊情况下的内存。 – Kevin