如何在编译期间设置线程堆栈大小?

How to set the thread stack size during compile time?

当尝试 运行 一个构建大型 clap::App (find the source here) 的程序时,我得到一个 Whosebug:thread '<main>' has overflowed its stack.

到目前为止,我无法弄清楚如何指示 rustc 增加堆栈大小以进行暴力解决。 RUST_MIN_STACK 似乎只适用于 运行 时间,即使在那里它似乎也没有任何效果。

生成代码后,我可能需要做的是将 SubCommand 创建移动到 运行 时间,这是我接下来要尝试的。

但是,您是否找到解决此问题的不同方法?

解决这个问题似乎很重要,因为构建器模式似乎很容易出现这个问题,如果构建的结构足够大且嵌套足够的话。

如何重现

git clone -b clap https://github.com/Byron/google-apis-rs
cd google-apis-rs
git checkout 9a8ae4b
make dfareporting2d1-cli-cargo ARGS=run

请注意,您需要我的 quasi 分支并在本地设置覆盖以允许使用最新的编译器构建。

➜  google-apis-rs git:(clap) rustc --version
rustc 1.1.0-nightly (97d4e76c2 2015-04-27) (built 2015-04-28)

在 Rust 中无法设置主线程的堆栈大小。事实上,在 Rust 运行time library (https://github.com/rust-lang/rust/blob/master/src/libstd/rt/mod.rs#L85).

中,在源代码级别做出了关于主线程堆栈大小的假设。

环境变量 RUST_MIN_STACK 会影响在非主线程的程序中创建的线程的堆栈大小,但您可以在 运行 时在源代码中轻松指定该值。

解决问题最直接的方法可能是 运行 在您创建的单独线程中拍手,这样您就可以控制其堆栈大小。

以这段代码为例:

extern crate clap;
use clap::App;
use std::thread;

fn main() {
    let child = thread::Builder::new().stack_size(32 * 1024 * 1024).spawn(move || {
        return App::new("example")
            .version("v1.0-beta")
            .args_from_usage("<INPUT> 'Sets the input file to use'")
            .get_matches();
    }).unwrap();

    let matches = child.join().unwrap();

    println!("INPUT is: {}", matches.value_of("INPUT").unwrap());
}

clap 似乎能够从子线程中正确终止应用程序,因此您的代码只需稍作修改即可工作。