gpt4 book ai didi

multithreading - 管理绿色线程

转载 作者:行者123 更新时间:2023-11-29 08:19:31 26 4
gpt4 key购买 nike

要在 Rust 中使用 M:N 线程模型,我会启动一个池并像往常一样开始生成任务。 The Green Documentation给出以下示例:

#![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()
});
}
}

如果您想动态添加另一个操作系统线程,可以这样做:

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();

有没有办法说使用 x 个操作系统线程,还是必须在代码中创建和管理它们?

最佳答案

根据 PoolConfig 的文档,创建新池时可以指定操作系统线程数:

let mut config = PoolConfig::new();
config.threads = 42u;
let mut pool = SchedPool::new(config);
// use your pool with 42 OS threads as you want

config.threads 的默认值由 std::rt::default_sched_threads() 给出

关于multithreading - 管理绿色线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25726084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com