views:

23

answers:

1

I'm trying to implement user threads in Linux kernel 2.4, and I ran into something problematic and unexpected.

Background: a thread basically executes a single function and dies, except that when I call thread_create for the first time it must turn main() into a thread as well (by default it is not a thread until the first call, which is also when all the related data structures are allocated).

Since a thread executes a function and dies, we don't need to "return" anywhere with it, but we do need to save the return value to be reclaimed later with thread_join, so the hack I came up with was: when I allocate the thread stack I place a return address that points to a thread_return_handler function, which deallocates the thread, makes it a zombie, and saves its return value for later. This works for "just run a function and die" threads, but is very problematic with the main thread. Since it actually is the main function, if it returns before the other threads finish the normal return mechanism kicks in, and deallocates all the shared resources, thus screwing up all the running threads.

I need to keep it from doing that. Any ideas on how it can be done?

+1  A: 

You could register a function with atexit() that is called at program termination. Note though that you can't tell the difference between calling exit() and returning from main().

...and that goes to the heart of the matter. Traditionally, returning from main() is the same as calling exit(), which means that it indicates that the entire process should be terminated - including all still-running threads. In other words, the "main thread" is special. Are you sure you can't just document that as expected behaviour? It's how other UNIX threading models tend to work, after all.

caf