Technology Sharing

How big is the stack of a thread in Android? Where is it set?

2024-07-11

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

In Android, the stack size of a thread can vary depending on different Android versions and thread types (such as main thread and child thread). The following is a detailed answer to the stack size of a thread in Android and how to set it:

Thread stack size

  1. Main thread stack size
    • By default, the stack size of the Android main thread is usually8MBThis is the initial stack space allocated by the system for the main thread, which is used to store method calling process, local variables, operand stack and other information.
  2. Child thread stack size
    • The stack size of a child thread is relatively small, and the specific size depends on the Android version. For example, in Android 6.0/7.0, the stack size of a child thread (including the GUARD area) is approximately1016KB; In Android 8.0, the stack size of the child thread (including the GUARD area) is approximately1008KB; In Android 9.0 and higher, the stack size of the child thread (excluding the GUARD area) is approximately1008KB, but the total size allocated by mmap (including STACK and GUARD) is1012KBor1016KB

Set thread stack size

In Android, you can set the thread stack size by calling the relevant functions of the POSIX thread (pthread) library. These functions are usually used in C or C++ code, because many of the underlying mechanisms of Android are based on these languages.

  1. Function to set thread stack size
    • pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize): This function is used to set the thread attribute objectattrThe stack size instacksize
    • In usepthread_createBefore creating a thread, you need to callpthread_attr_initInitialize the thread attributes object and then usepthread_attr_setstacksizeSet the stack size and finally create a thread using the set property object.
  2. Sample Code
     

    c

    #include