感觉也不像是数据竞争 代码如下:
use async_std::channel::Receiver;
use async_std::fs::File;
use async_std::prelude::*;
use std::path::PathBuf;
pub struct Output {
    rec: Receiver<String>,
    outfile: Option<PathBuf>,
}
impl Output {
    pub async fn new(rec: Receiver<String>, outfile: Option<PathBuf>) -> Output {
        Output {
            rec,
            outfile,
        }
    }
    pub async fn run(&self) {
        let output: Option<File>;
        match &self.outfile {
            None => {
                output = None
            }
            Some(file) => {
                output = Some(File::create(file).await.unwrap());
            }
        };
        'a:
        loop {
            match self.rec.recv().await {
                Ok(r) => {
                    match &self.outfile {
                        None => {
                            println!("{}", r);
                        }
                        Some(..) => {
                            println!("{}", r);
                            let r = format!("{} \n", r);
                            output.as_ref().unwrap().write(r.as_bytes()).await.unwrap();
                        }
                    }
                }
                Err(_) => {
                    break 'a;
                }
            }
        }
    }
}
数据写入channel里面 轮询channel写入到文件当中
log输出没有问题 没有乱序
127.0.0.1:139
127.0.0.1:445
127.0.0.1:631
127.0.0.1:3306
127.0.0.1:6379
127.0.0.1:5432
127.0.0.1:6942
127.0.0.1:27017
127.0.0.1:63342
但是输出到文件 乱了
127.0.0.1:139 
127.0.0.1:445 
127.0.0.1:631 
127.0.0.1:3306 127.0.0.1:6379
127.0.0.1:5432127.0.0.1:6942
127.0.0.1:2701127.0.0.1:63342
我把 let output: Option; 加锁 let output: Option<Mutex>; 还是乱序?
具体:https://github.com/dollarkillerx/blackwater/blob/main/src/output.rs
	    
	    
		1
	    
	    
	    共 3 条评论, 1 页
	
	
    
评论区
写评论谢谢大佬
--
👇
whfuyn: https://docs.rs/async-std/1.8.0/async_std/io/trait.Write.html#method.write
write的语义不是全部写进去,而是写一些,写了多少会返回。用
write_all吧。https://docs.rs/async-std/1.8.0/async_std/io/trait.Write.html#method.write
write的语义不是全部写进去,而是写一些,写了多少会返回。用
write_all吧。修改成同步的
std::fs::File就没有乱序了???