Search code examples
c++windowsmultithreadingstacklock-free

How to programmatically tell if two variables are on the same stack? (in Windows)


I'm in a thread. I have an address. Is that address from a variable on the same stack that I'm using?

static int *address;

void A()
{
    int x;
    atomic::CAS(address, 0, &x); // ie address = &x
    // ...
}

void B()
{
   int y;
   int * addr = atomic::read(address); // ie addr = address
   if (addr && on_same_stack(&y, addr))
   {
      // B() called from A()
   }
   else
   {
      // B() called from different thread than A()
   }
}

I need to implement on_same_stack(addr1, addr2). I know that the stack(s) on Windows grow as needed, but I also know that there is a limit to the growth, and that (in debug at least) there is stack-overflow-checking code on every function call. So I think it can be done.

Now, I also know that I could/should use thread IDs, etc. But I'm trying to implement some tricky lock-free coding here, and I don't really have the room to store the thread IDs, just a single pointer. (I'm hoping to avoid CMPXCH16). Please trust me that I somewhat know what I'm doing :-).

This is for Windows-only for now. But the more portable the better. (NT/XP/7/CE?)

P.S. this site is called "stackoverflow" so it should be the right place to ask, shouldn't it? :-)

EDIT: adding context, since everyone is asking. I'm implementing a custom call_once similar to pthread_once or boost.threads call_once. I'm attempting to check for recursion. I am very limited with what I have to work with. I can't add function parameters. I can't make assumptions about what the rest of the program is doing, like how much TLS they are already using. Etc. I can only code inside my one function, and make no changes or assumptions about anything outside of that.

Thanks for your questions/answers.


Solution

  • How about something crazy like (untested):

    declspec(__thread) void* stackBottom;
    
    void Thread1Routine(void* arg)
    {
      volatile int bottom;
      stackBottom = ⊥
    
      ... (do stuff which ends up calling on_same_stack()) ...
    }
    
    
    bool on_same_stack(void* p)
    {
      volatile int top;
      return ((LONG_PTR)p >= (LONG_PTR)&top) && ((LONG_PTR)p <= (LONG_PTR)stackBottom);
    }
    

    (edited to remove theoretical register-based arg passing issues)