How to set the stacksize with C++11 std::thread

后端 未结 6 1714
野性不改
野性不改 2020-11-29 03:06

I\'ve been trying to familiarize myself with the std::thread library in C++11, and have arrived at a stumbling block.

Initially I come from a posix

6条回答
  •  暖寄归人
    2020-11-29 03:59

    I have also been investigating this issue. For some applications, the default stack size is not adequate. Examples: the program does deep recursion dependent on the specific problem it is solving; the program needs to create many threads and memory consumption is an issue.

    Here is a summary of (partial) solutions / workarounds I found:

    • g++ supports a -fsplit-stack option on Linux. See for more information about Split stacks. Here is summary from their website:

    The goal of split stacks is to permit a discontiguous stack which is grown automatically as needed. This means that you can run multiple threads, each starting with a small stack, and have the stack grow and shrink as required by the program.

    Remark: -fsplit-stack only worked for me after I started using the gold linker. It seems clang++ will also support this flag. The version I tried (clang++ 3.3) crashed when trying to compile my application using the flag -fsplit-stack.

    • On Linux, set the stack size by executing ulimit -s before starting your application. size is the stack size in Kbs. Remark: the command unlimit -s unlimited did not affect the size of threads created with std::thread. When I used ulimit -s unlimited, the main thread could grow, but the threads created with std::thread had the default size.

    • On Windows using Visual Studio, we can use use the linker /STACK parameter or /STACKSIZE in the module definition file, this is the default size for all created threads. See this link for more information. We can also modify this parameter in any executable using the command line tool EDITBIN.

    • On Windows using mingw g++, we can use the option -Wl,--stack,. For some reason, when using cygwin g++, this flag only affects the size of the main thread.

    Approaches that did not work for me:

    • ulimit -s on OSX. It affects only the size of the main thread. Moreover, the Mac OSX default for a pthread stack size is 512kB.

    • setrlimit only affects the size of the main thread on Linux and OSX. On cygwin, it never worked for me, it seems it always returns an error.

    For OSX, the only alternative seems to use boost::thread instead of std::thread, but this is not nice if we want to stick with the standard. I hope g++ and clang++ will also support -fsplit-stack on OSX in the future.

提交回复
热议问题