为什么我的Rust线程不能并行运行? [英] Why are my Rust threads not running in parallel?

查看:248
本文介绍了为什么我的Rust线程不能并行运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望启动X个线程,这将向代码内的指定服务器触发X个请求.目前,我的应用程序正在等待每个线程和X请求完成,然后再分配下一个线程.

I wish to spin up X threads which will fire X requests to the specified server within the code. Currently, my application is waiting for each thread and X requests to finish before spinning up the next one.

我该如何进行异步操作?

How can I go about doing this async?

extern crate hyper;
extern crate time;

use hyper::header::Connection;
use hyper::Client;
use std::sync::{Arc, Mutex};
use std::thread;
use time::*;

struct Request {
    elapsed_time: f64,
}

impl Request {
    fn new(elapsed_time: f64) -> Request {
        Request {
            elapsed_time: elapsed_time,
        }
    }
}

fn main() {
    let requests = Arc::new(Mutex::new(Vec::new()));

    for _x in 0..100 {
        println!("Spinning up thread...");

        let mut client = Client::new();
        let thread_items = requests.clone();

        let handle = thread::spawn(move || {
            for _x in 0..100 {
                println!("Firing the request");
                let start = time::precise_time_s();

                let _res = client
                    .get("http://jacob.uk.com")
                    .header(Connection::close())
                    .send()
                    .unwrap();

                let end = time::precise_time_s();

                thread_items
                    .lock()
                    .unwrap()
                    .push((Request::new(end - start)));
            }
        });

        handle.join().unwrap();
    }
}

程序输出:

Spinning up thread...
Firing request
Firing request
Firing request
Firing request
Spinning up thread...
Firing request
Firing request
Firing request
Firing request
Spinning up thread...
Firing request
Firing request
Firing request
Firing request

推荐答案

您的罪魁祸首是此行:

handle.join().unwrap();

您在循环中执行一个线程,然后在启动线程后立即将其join插入主线程.

You execute a thread in the loop, and then right after starting the thread you join it into the main thread.

您可以做的是创建一个Vec并将所有手柄放置在vec中.然后,在另一个循环中,join所有句柄.

What you could do, is to create a Vec and put all the handles in the vec. Then, in another loop, you join all the handles.

另一种可能性是不加入线程,而让它们自然退出,但是那时您将不知道所有线程何时完成.如@delnan所述,这可能允许主线程在生成的线程退出之前退出.这将导致所有生成的线程被杀死,而不是让它们运行到终止.

Another possibility is to simply not join the threads, and let them exit naturally, but then you won't know when all of them are done. Which, as @delnan notes, might allow the main thread to exit before the spawned threads exit. This causes all the spawned threads to be killed instead of letting them run to termination.

这篇关于为什么我的Rust线程不能并行运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆