I was commenting on an answer that thread-local storage is nice and recalled another informative discussion about exceptions where I supposed
The only special thing about the
execution environment within the throw
block is that the exception object is
referenced by rethrow.
Putting two and two together, wouldn't executing an entire thread inside a function-catch-block of its main function imbue it with thread-local storage?
It seems to work fine:
#include <iostream>
#include <pthread.h>
using namespace std;
struct thlocal {
string name;
thlocal( string const &n ) : name(n) {}
};
thlocal &get_thread() {
try {
throw;
} catch( thlocal &local ) {
return local;
}
}
void print_thread() {
cerr << get_thread().name << endl;
}
void *kid( void *local_v ) try {
thlocal &local = * static_cast< thlocal * >( local_v );
throw local;
} catch( thlocal & ) {
print_thread();
return NULL;
}
int main() try {
thlocal local( "main" );
throw local;
} catch( thlocal & ) {
print_thread();
pthread_t th;
thlocal kid_local( "kid" );
pthread_create( &th, NULL, &kid, &kid_local );
pthread_join( th, NULL );
print_thread();
return 0;
}
Is this novel or well-characterized? Was my initial premise correct? What kind of overhead does get_thread incur in, say, GCC and VC++?
It would require throwing only exceptions derived from struct thlocal, but altogether this doesn't feel like an unproductive insomnia-ridden Sunday morning…