septag/sx

Freeing tls data on thread exit

Closed this issue · 7 comments

Currently, there is :

  • sx_tls_create
  • sx_tls_destroy
  • sx_tls_get
  • sx_tls_set

Is there a way to specify a callback to be invoked on thread exit so the tls data for the exiting thread can be cleaned up?

why can't you clean it up in thread callback ?

int thread_cb(void* user_data1, void* user_data2)
{
    sx_tls t = sx_tls_create();
    while(!quit) {
        // do work
    }
    sx_tls_destroy(t);
    return 0;
}

or destroy it after sx_thread_destroy call

Because I'm writing a library that needs TLS for data but does not create threads itself. I'm hoping to get access to functionality similar to:

void pthread_cleanup_push(void (*routine)(void *), void *arg);

reference

I was looking for the same thing.
In C11 there is tss_create which takes a function pointer executed when the thread ended. Would be nice if sx follows the same approach withsx_tls_create.

Sorry for late reply.
I understand. If the problem is because you don't own the threads, then I think it's gonna be hard to solve for windows. I have looked into the Win32 APIs and didn't find any destructor hooks.

Any ideas/suggestions or PR are greatly welcomed.

after some research, I see two approaches

1 - emulate it
The mesa project provides a windows c11 implementation: https://gitlab.freedesktop.org/mesa/mesa/blob/master/include/c11
But this won't work for threads created externally.

The only way to check if a thread has ended on win32 is hacky, by using WaitForSingleObject, passing the thread handle.
It would require a background timer that would track every threads periodically. not so great.

2 - use c++11

using the thread_local attribute, class instances have their ctor/dtor called.
maybe this could be wrapped behind sx 's api.

Using C++11 sounds like a workable idea. I think there is an issue with thread_local on AppleClang. You could look at how boost solves this with at_thread_exit, to see if it can be done in C natively, or how to do it with C++.

I apologize for late replies. I'm currently switching jobs and been very busy. Also thank you for your suggestions.
Obviously, the first one is not applicable because we definitely don't want to create a thread for that. The second one is more sane but it breaks the C compatibility of the library (library should be compiled with a C compiler), so I think I will leave it for now unless a better solution is found. In my opinion the added complexity and language requirement does not worth it for this minor feature.
In such cases, you can easily do that yourself instead of using the tls of sx because the underlying code is very small and manageable.