开发者

Implementing join function in a user level thread library

I am trying to implement a user level thread library as part of a project. My focus is on the join function. Lets say that Thread1 calls join function on Thread2. What i need to do is get the return value/argument supplied to pthread_exit() from Thread2 and store it in the memory location specified in jo开发者_如何学Pythonin function argument.

But, how do i get the return value of another thread?

Any help will be appreciated. Thanks


Here is an example taken from the GnuPth(pth_lib.c) user-level threading library, which shows the implementation of the exit and join functions, respectively. I simplified the code to highlight the return value handling.

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
}

and the corresponding 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;
}


You could create storage for the return value in the application or process context, initialized when your threads library initializes. Your pthread_exit would fill the value and your join would use the threadid to retrieve it - I think this will only work for non-dynamically allocated return values though.


I'm interesting about the meta-info for individual thread in you implementation. Return value could be one of items stored in that of a thread, besides ID, stack pointer and so on.

When pthread_exit() is called, such information should be dumped to one or more data structures by scheduler, so that other thread can consult them when needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜