Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to release the object in a TLS-slot at thread exit on Windows?

for example, in a multi-thread program:

struct TLSObject;

void foo()
{
    TLSObject* p = TlsGetValue(slot);
    if (p == 0) {
        p = new TLSObject;
        TlsSetValue(slot, p);
    }
    // doing something with p
}

the first time to call foo() in any thread will makes a new TLSObject.

my question is: How to delete a TLSObject(if I don't use boost::thread and boost::thread_specific_ptr) ?

boost::thread_specific_ptr can do cleanup work at thread exit, but it depends on boost::thread I guess, not for normal OS thread, and it's slow.

like image 963
amanjiang Avatar asked Dec 26 '22 21:12

amanjiang


1 Answers

Instead of TlsAlloc, use FlsAlloc (and related Fls* functions). With FLS, you register a cleanup callback which the OS will call on the thread before the thread terminates, giving you the opportunity to clean up.

like image 72
James McNellis Avatar answered May 14 '23 18:05

James McNellis