Prak
Prak

Reputation: 1069

Stack address for Thread and the main process

I have a question related to the memory address of thread and process. The question is:- In normal call like

int func(int a, int b){
    int c;
    c = a + b;
    return c;
}         

int main(){
    int ret = func(a,b);
     return 0;
}

In the above function call to function func, the function variable a and b will get stored on stack. Please correct me, If I am wrong.

Now the other situation is when we are creating threads from the main process.

void * func(void *dummy_ptr){
    int c;
    c = a + b;
    pthread_exit();
}         

int main(){
    pthread_t  id;
    int ret = pthread_create(&id, NULL, & func(), NULL);
    return 0;
}

My question is where the variable of the pthread_create will get stored. Is it getting stored on Stack of main, or on the stack of thread.

Upvotes: 0

Views: 449

Answers (2)

Suvarna Pattayil
Suvarna Pattayil

Reputation: 5239

The variable pthread_t id is local to main so it must be created on the stack of main.

When main finishes execution and,

  • You don't have a pthread_join in main to wait until the thread terminates.
  • The thread is not detached.

main exits causing all other threads to terminate abrubtly (kill).

Upvotes: 0

charliehorse55
charliehorse55

Reputation: 1990

pthread_create allocates space for the new thread's stack in the heap. So the variables inside of func are stored on the thread's stack, which itself is located in the program's heap.

Upvotes: 1

Related Questions