Search code examples
clinuxmultithreadingstackpthread-exit

how to save a thread stack before it exits?


I'm working on a multi-threading project and I need to make a copy of a thread's stack at some point in code (I need a pointer to that). because I'm going to need that pointer after this thread is exited (and it's stack is freed). It would also do the job if I could somehow tell pthread_exit() not to free the stack of thread!

PS: The reason behind this is that I want to use setcontext(ucontext_t*) later when this thread is actually dead.


Solution

  • As was mentioned, this may be a case of the XY problem. However, the solution is to use a pthread_mutex_t in each thread.

    The function creating the thread would create the pthread_mutext_t and pass it to the thread.

    pthread_t tid;
    pthread_mutext_t mutex;
    
    pthread_mutex_init(&mutex, NULL);
    pthread_mutex_lock(&mutex);
    
    pthread_create(&tid, NULL, fun, &mutex);
    
    // do stuff
    
    pthread_mutex_unlock(&mutex);
    

    The thread function would be as follows...

    void fun(void* arg) {
    
      pthread_mutex_t* mutex = (pthread_mutex_t*) arg;
      pthread_mutex_lock(mutex);
    
      // do stuff
    }
    

    If you need to do this asynchronously, you can register a signal handler for SIGUSR1 and SIGUSR2 and use pause to unschedule the thread.

    signal(SIGUSR1, on_usr1);
    signal(SIGUSR2, on_usr2);
    
    void on_usr1(int sig) {
    
      pause();
    }
    
    void on_usr2(int sig) {
    }
    

    Then use pthread_kill to raise the signal to the thread...

    pthread_kill(tid, SIGUSR1);