Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 894141
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T14:20:03+00:00 2026-05-15T14:20:03+00:00

I was commenting on an answer that thread-local storage is nice and recalled another

  • 0

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, albeit slowly. Is this novel or well-characterized? Is there another way of solving the problem? Was my initial premise correct? What kind of overhead does get_thread incur on your platform? What’s the potential for optimization?

#include <iostream>
#include <pthread.h>
using namespace std;

struct thlocal {
    string name;
    thlocal( string const &n ) : name(n) {}
};

struct thread_exception_base {
    thlocal &th;
    thread_exception_base( thlocal &in_th ) : th( in_th ) {}
    thread_exception_base( thread_exception_base const &in ) : th( in.th ) {}
};

thlocal &get_thread() throw() {
    try {
        throw;
    } catch( thread_exception_base &local ) {
        return local.th;
    }
}

void print_thread() {
    cerr << get_thread().name << endl;
}

void *kid( void *local_v ) try {
    thlocal &local = * static_cast< thlocal * >( local_v );
    throw thread_exception_base( local );
} catch( thread_exception_base & ) {
    print_thread();

    return NULL;
}

int main() {
    thlocal local( "main" );
    try {
        throw thread_exception_base( local );
    } catch( thread_exception_base & ) {
        print_thread();

        pthread_t th;
        thlocal kid_local( "kid" );
        pthread_create( &th, NULL, &kid, &kid_local );
        pthread_join( th, NULL );

        print_thread();
    }

    return 0;
}

This does require defining new exception classes derived from thread_exception_base, initializing the base with get_thread(), but altogether this doesn’t feel like an unproductive insomnia-ridden Sunday morning…

EDIT: Looks like GCC makes three calls to pthread_getspecific in get_thread. EDIT: and a lot of nasty introspection into the stack, environment, and executable format to find the catch block I missed on the first walkthrough. This looks highly platform-dependent, as GCC is calling some libunwind from the OS. Overhead on the order of 4000 cycles. I suppose it also has to traverse the class hierarchy but that can be kept under control.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T14:20:04+00:00Added an answer on May 15, 2026 at 2:20 pm

    In the playful spirit of the question, I offer this horrifying nightmare creation:

    class tls
    {
        void push(void *ptr)
        {
            // allocate a string to store the hex ptr 
            // and the hex of its own address
            char *str = new char[100];
            sprintf(str, " |%x|%x", ptr, str);
            strtok(str, "|");
        }
    
        template <class Ptr>
        Ptr *next()
        {
            // retrieve the next pointer token
            return reinterpret_cast<Ptr *>(strtoul(strtok(0, "|"), 0, 16));
        }
    
        void *pop()
        {
            // retrieve (and forget) a previously stored pointer
            void *ptr = next<void>();
            delete[] next<char>();
            return ptr;
        }
    
        // private constructor/destructor
        tls() { push(0); }
        ~tls() { pop(); }
    
    public:
        static tls &singleton()
        {
            static tls i;
            return i;
        }
    
        void *set(void *ptr)
        {
            void *old = pop();
            push(ptr);
            return old;
        }
    
        void *get()
        {
            // forget and restore on each access
            void *ptr = pop();
            push(ptr);
            return ptr;
        }
    };
    

    Taking advantage of the fact that according to the C++ standard, strtok stashes its first argument so that subsequent calls can pass 0 to retrieve further tokens from the same string, so therefore in a thread-aware implementation it must be using TLS.

    example *e = new example;
    
    tls::singleton().set(e);
    
    example *e2 = reinterpret_cast<example *>(tls::singleton().get());
    

    So as long as strtok is not used in the intended way anywhere else in the program, we have another spare TLS slot.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We all know that commenting our code is an important part of coding style
There is a lot of conversation about commenting code, but how about commenting on
Duplicate What are your hard rules about commenting? A Developer I work with had
i've got a commenting system in our database. Just like stackoverflow -> each post
I've been given some code with commenting unlike anything I've come across before: //{{{
A client is asking to incorporate commenting on their news articles. They're using the
One of the most common dilemmas I have when commenting code is how to
Is there a standard convention (like phpdoc or python's docstring) for commenting C# code
Recently saw someone commending another user on their use of sizeof var instead of
I'm chasing a production bug that's intermittent enough to be a real bastich to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.