Would a race condition between pthread_join() and pthread_exit() potentially cause a SEGV?
===

I am getting a SEGV in C++ that I cannot easily reproduce (it occurs in about one in 100,000 test runs) in my call to `pthread_join()` as my application is shutting down.  I checked the value of errno and it is zero.  This is running on Centos v4.

Under what conditions would `pthread_join()` get a SEGV? This might be some kind of race condition since it is extremely rare.

My current working hypothesis is that `pthread_join()` is being called while `pthread_exit()` is still running in the other thread and that this somehow leads to a SEGV.

The failing code getting SEGV in the main thread during application exit looks roughly like this:

    // During application startup, this function is called to create the child thread:

    return_val = pthread_create(&_threadId, &attr,
                                (void *(*)(void *))initialize,
                                (void *)this);

    // Later during exit the following code is executed in the main thread:

    // This main thread waits for the child thread exit request to finish:

    // Release condition so child thread will exit:
    releaseCond(mtx(), startCond(), &startCount);

    // Wait until the child thread is done exiting so we don't delete memory it is
    // using while it is shutting down.
    waitOnCond(mtx(), endCond(), &endCount, 0);
    // The above wait completes at the point that the child thread is about
    // to call pthread_exit().

    // It is unspecified whether a thread that has exited but remains unjoined
    // counts against {PTHREAD_THREADS_MAX}, hence we must do pthread_join() to
    // avoid possibly leaking the threads we destroy.
    pthread_join(_threadId, NULL); // SEGV in here!!!

The child thread which is being joined on exit runs the following code which begins at the point above where `releaseCond()` is called in the main thread:

    // Wait for main thread to tell us to exit:
    waitOnCond(mtx(), startCond(), &startCount);

    // Tell the main thread we are done so it will do pthread_join():
    releaseCond(mtx(), endCond(), &endCount);
    // At this point the main thread could call pthread_join() while we 
    // call pthread_exit().

    pthread_exit(NULL);

The thread appeared to come up properly and no error codes were produced during its creation during application startup and the thread performed its task correctly which took around five seconds before the application exited.

What might cause this rare SEGV to occur and how might I program defensively against it.  Could this be a bug in the operating system that needs to be patched?

If my hypothesis is correct that I have a race condition between `pthread_exit()` and `pthread_join()` how might I fix this issue?