[英]Managing green threads
To use the M:N
threading model in Rust, I would get a pool going and just start spawning tasks as usual. 要在Rust中使用M:N
线程模型,我需要一个池,然后像往常一样开始生成任务。 The Green Documentation gives the following example: 绿色文档提供以下示例:
#![feature(phase)]
#[phase(plugin)] extern crate green;
green_start!(main)
fn main() {
// Running inside a green pool
// Spawn more green threads?
for x in some_thing.iter() {
spawn(proc() {
some_task()
});
}
}
If you wanted to dynamically add another OS thread, one would do something like this: 如果要动态添加另一个OS线程,则可以执行以下操作:
extern crate green;
extern crate rustuv;
use std::task::TaskBuilder;
use green::{SchedPool, PoolConfig, GreenTaskBuilder};
let mut config = PoolConfig::new();
// Optional: Set the event loop to be rustuv's to allow I/O to work
config.event_loop_factory = rustuv::event_loop;
let mut pool = SchedPool::new(config);
// Spawn tasks into the pool of schedulers
TaskBuilder::new().green(&mut pool).spawn(proc() {
// this code is running inside the pool of schedulers
spawn(proc() {
// this code is also running inside the same scheduler pool
});
});
// Dynamically add a new scheduler to the scheduler pool. This adds another
// OS thread that green threads can be multiplexed on to.
let mut handle = pool.spawn_sched();
// Pin a task to the spawned scheduler
TaskBuilder::new().green_pinned(&mut pool, &mut handle).spawn(proc() {
/* ... */
});
// Handles keep schedulers alive, so be sure to drop all handles before
// destroying the sched pool
drop(handle);
// Required to shut down this scheduler pool.
// The task will fail if `shutdown` is not called.
pool.shutdown();
Is there a way to say use x num of OS threads, or do they have to be created and managed within the code? 有没有办法说使用x数量的OS线程,还是必须在代码中创建和管理它们?
According to the documentation of PoolConfig
, the number of OS threads can be specified when creating a new pool : 根据PoolConfig
的文档,可以在创建新池时指定OS线程数:
let mut config = PoolConfig::new();
config.threads = 42u;
let mut pool = SchedPool::new(config);
// use your pool with 42 OS threads as you want
The default value of config.threads
is given by std::rt::default_sched_threads()
config.threads
的默认值由std::rt::default_sched_threads()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.