#Windows Terminating Process With Main Thread

1 messages · Page 1 of 1 (latest)

hasty roost
#

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

GitHub

Small Portable C Library For Multithreading. Contribute to AlexCodesApps/CThreads development by creating an account on GitHub.

true groveBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

shy bay
#

exiting the main thread is exiting the process. why do you think the detach threads would magically just live on beyond the end of the process?

hasty roost
hollow cargo
#

well you can't do that bing_shrug

#

this is precisely why detach is pretty much never not wrong

#

join your threads, problem solved