Junior — Middle
What memory area is allocated when a new thread is started?
sobes.tech AI
Answer from AI
When a new thread of execution is started in C/C++, a separate stack memory is usually allocated for that thread. The stack is used to store local variables, return addresses, and other data necessary for executing functions within that thread. Besides the stack, the thread shares the process's address space with other threads, including the heap and static data.
Example of creating a thread with stack allocation (at the OS or library level, e.g., pthreads):
#include <pthread.h>
#include <stdio.h>
void* thread_func(void* arg) {
int local_var = 5; // stored on the thread's stack
printf("Local var: %d\n", local_var);
return NULL;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, thread_func, NULL);
pthread_join(thread, NULL);
return 0;
}
Here, the OS allocates a separate stack for each thread so that local variables do not overlap between threads.