ozma
ozma

Reputation: 1803

(edit) keep threads alive without changing main

I would like to be able to start a pthread and that it will stay alive Even if main() is done.

I don't have access to main().

the normal behavior is that if a thread is started and did't "join_thread" from main() it will be terminated when main done running.

in java, the default is that thread that was invoked will stay alive. Only when all threads are done the process will terminate. no explicit call to java "join_thread" is required.

Upvotes: 0

Views: 195

Answers (2)

Valeri Atamaniouk
Valeri Atamaniouk

Reputation: 5163

You can try to play with atexit function.

static pthread_t thread_ids[128];
static size_t    thread_count;
static pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALIZER;

static void join_all_threads()
{
    size_t i;
    for (i = 0; i < thread_count; i++)
    {
        pthread_join(&thread_ids[i], NULL);
    }
    thread_count = 0;
}

Somewhere in the code:

...
atexit(join_all_threads);
...

In the thread code:

void *my_thread_fn(void *arg)
{
    pthread_mutex_lock(&thread_mutex);
    thread_ids[thread_count++] = pthread_self();
    pthread_mutex_unlock(&thread_mutex);

    ...
}

Edit: added on_exit

If you happen to have on_exit function, then it becomes simpler:

void my_thrad_join(int code, void *arg)
{
    pthread_join((pthread_t)arg);
}

void *my_thread_fn(void *arg)
{
    on_exit(my_thread_join, (void*)pthread_self());
}

Upvotes: 0

UltraInstinct
UltraInstinct

Reputation: 44444

You could end your main() with a pthread_exit(..) instead of a return 0. This function call doesn't return. That way, your main thread would exit but your process wont finish.

The process would end when all threads are done, or exit(..) is called.

Upvotes: 2

Related Questions