I am developing a cross platform library for multithreading and for the most part, it is actually pretty functional. However, there is one pesky bug that keeps cropping up while testing the Windows backend. That being when the main thread terminates, even if I detach the other threads, the whole program tends to crash unceremoniously after some random amount of time. The snippet below exhibits the problem behavior
#include <stdio.h>
#include <stdlib.h>
#include "../threads.h"
struct State {
Mutex mutex;
int resource;
};
int run(void * arg) {
struct State * state = arg;
mutex_lock(&state->mutex);
int item = ++state->resource;
printf("value [%d]\n", item);
mutex_unlock(&state->mutex);
printf("ending [%d]\n", item);
return item;
}
int main() {
struct State state;
mutex_init(&state.mutex);
state.resource = 0;
Thread threads[10];
for (int i = 0; i < 10; ++i) {
if (!thread_start(threads + i, run, &state))
abort();
}
for (int i = 0; i < 10; ++i) {
thread_detach(threads + i);
}
printf("main thread is ending\n");
thread_exit(255);
}
thread_start works fine, thread_detach isnt much more than a wrapper around CloseHandle, and thread_exit is a near 1-1 wrapper of ExitThread,
yet it just won't work correctly. Also when it crashes like this, the exit code of the program is meaningless garbage. I've looked at resources online and tried using _beginthreadex and the like but the issue doesn't go away. I know a work arround but due to the fact that the library doesn't have a dedicated entry point, it is a somewhat expensive ugly hack to add all the neccesary bookeeping and thread synchronization that I would like to avoid. Either that or I change the library interface to have a dedicated init function still with some overhead, or just disallow this outright.
What are my options?
https://github.com/AlexCodesApps/CThreads
