Pete's Log: silly pthreads
Entry #1073, (Coding, Hacking, & CS stuff)(posted when I was 23 years old.)
I found myself rather worried today that I was leaking threads in some unimaginable fashion in the pilsner. But then I discovered it was all just due to an oddity in the linux pthreads implementation. please forgive the fact that I'm synchronizing with sleep statements, and consider the following code:
#include <stdio.h> #include <pthread.h> #include <unistd.h> void* foo(void* f) { printf("now 2\n"); sleep(3); printf("now 3\n"); return NULL; } int main() { pthread_t t; printf("now 1\n"); sleep(3); pthread_create(&t, NULL, foo, NULL); sleep(6); pthread_join(t, NULL); printf("now 4\n"); sleep(3); return 0; }
If you compile this code and call the binary threadfu, for example, and then run it and do a "ps aux | grep threadfu" each time it prints out a "now #" ... you may find the same odd results I did. At "now 1" there was one threadfu process. At "now 2" there were three. At "now 3" I see two threadfu processes, and at "now 4" I still see two threadfu processes. At every point, other than "now 1" there was one threadfu process more than I expected. Odd. But at least this should indicate that I'm not leaking threads. The linux pthread implementation seems to be doing that. But at least if I throw more pthread_create's into the code there's only one extra process and not one per thread. I'm guessing the extra process probably serves some useful purpose, such as reaping dead threads.