For some reason, I create my own stacks for all the threads in my application by using pthread_attr_setstack function before calling pthread_create. However, I also want to have a custom stack for my main thread. How can I achieve that?
If that is not possible, how can I at least get the stack address and size of the main thread?
At a minimum, a thread's stack is used to store the location of a return address provided by the caller in order to allow return statements to return to the correct location. The stack is often used to store variables of fixed length local to the currently active functions.
Multithreaded processes have multiple threads that perform tasks concurrently. Just like the thread that runs the code in main() , additional threads each use a function as an entry point. To maintain the logical flow of these additional threads, each thread is assigned a separate stack.
It is important to distinguish between these two types of process memory because each thread will have its own stack, but all the threads in a process will share the heap. Threads are sometimes called lightweight processes because they have their own stack but can access shared data.
Every thread has its own execution stack. This is the crucial part; this means that difference threads can be executing different functions, at the same time, without interfering with each other.
However, I also want to have a custom stack for my main thread.
You can't. Stack for main thread is created by OS elf loader. The size of main stack is not fixed statically (only upper limit does, via ulimit -s). OS will grow the stack each time when it is needed.
How can I achieve that?
You can only switch a stack by resetting %sp,%bp registers. You should do this very carefully and it will be better to reset them back before exiting.
If that is not possible, how can I at least get the stack address
You can estimate stack address by:
int main()
{
int a;
printf("Stackaddress is near %p\n", &a);
}
And you can read /proc/pid/maps
file of your application and check the address range marked [stack]
and size of the main thread?
Size of the main stack is not fixed. This stack is almost empty (contains argv/envp/auxp - filled by OS) when program starts; and it will grow (not shrink) at every access to yet unused stack page. This is a special case of page fault, OS will detect that page fault looks like stack access and will give more physical pages into virtual address space of application.
Since the main function is called before any thread-specific initialization is done, I don't think that you can influence its stack. However, you could simply write a wrapper for main that starts a thread to execute the usual code of main and then simply waits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With