当前位置: 首页 > news >正文

文盘Rust -- Mutex解决并发写文件乱序问题 | 京东云技术团队

在实际开发过程中,我们可能会遇到并发写文件的场景,如果处理不当很可能出现文件内容乱序问题。下面我们通过一个示例程序描述这一过程并给出解决该问题的方法。

use std::{fs::{self, File, OpenOptions},io::{Write},sync::Arc,time::{SystemTime, UNIX_EPOCH},
};
use tokio::task::JoinSet;fn main() {println!("parallel write file!");let max_tasks = 200;let _ = fs::remove_file("/tmp/parallel");let file_ref = OpenOptions::new().create(true).write(true).append(true).open("/tmp/parallel").unwrap();let mut set: JoinSet<()> = JoinSet::new();let rt = tokio::runtime::Runtime::new().unwrap();rt.block_on(async {loop {while set.len() >= max_tasks {set.join_next().await;}未做写互斥函数let mut file_ref = OpenOptions::new().create(true).write(true).append(true).open("/tmp/parallel").unwrap();set.spawn(async move { write_line(&mut file_ref) });}});
}fn write_line(file: &mut File) {for i in 0..1000 {let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();let mut content = now.as_secs().to_string();content.push_str("_");content.push_str(&i.to_string());file.write_all(content.as_bytes()).unwrap();file.write_all("\n".as_bytes()).unwrap();file.write_all("\n".as_bytes()).unwrap();}
}

代码不复杂,tokio 实现一个并发runtime,写文件函数是直接写时间戳,为了方便展示乱序所以写入两次换行。

输出的文本大概长这样

1691287258_9791691287258_7931691287258_3011691287258_7431691287258_6031691287258_8941691287258_471691287258_895
1691287258_5531691287258_950
1691287258_9801691287258_48
1691287258_3021691287258_896
1691287258_7441691287258_6041691287258_554

很明显,写入并未达到预期,间隔并不平均,函数内部的执行步骤是乱序的。

我们把上面的程序改造一下

use std::{fs::{self, File, OpenOptions},io::Write,sync::Arc,time::{SystemTime, UNIX_EPOCH},
};
use tokio::sync::Mutex;
use tokio::task::JoinSet;fn main() {println!("parallel write file!");let max_tasks = 200;let _ = fs::remove_file("/tmp/parallel");let file_ref = OpenOptions::new().create(true).write(true).append(true).open("/tmp/parallel").unwrap();let f = Arc::new(Mutex::new(file_ref));let mut set: JoinSet<()> = JoinSet::new();let rt = tokio::runtime::Runtime::new().unwrap();rt.block_on(async {loop {while set.len() >= max_tasks {set.join_next().await;}let mut file = Arc::clone(&f);set.spawn(async move { write_line_mutex(&mut file).await });}});
}async fn write_line_mutex(mutex_file: &Arc<Mutex<File>>) {for i in 0..1000 {let mut f = mutex_file.lock().await;let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();let mut content = now.as_secs().to_string();content.push_str("_");content.push_str(&i.to_string());f.write_all(content.as_bytes()).unwrap();f.write_all("\n".as_bytes()).unwrap();f.write_all("\n".as_bytes()).unwrap();}
}

这次我们用到了tokio::sync::Mutex,write_line_mutex函数在每次执行写任务以前先获取文件互斥锁。

看看这次的文件内容

1691288040_3741691288040_3741691288040_3741691288040_3751691288040_3741691288040_3741691288040_3741691288040_3741691288040_3741691288040_3741691288040_3741691288040_3741691288040_3741691288040_3741691288040_3751691288040_3751691288040_3741691288040_3751691288040_3751691288040_3751691288040_3751691288040_3751691288040_3751691288040_3751691288040_3751691288040_3751691288040_375

写入的格式正确,保证每次函数写函数完整执行。

关于文件写互斥这点事儿,今儿就聊到这。

完整源码

作者:京东科技 贾世闻

来源:京东云开发者社区

http://www.lryc.cn/news/124484.html

相关文章:

  • 数据结构算法--2 冒泡排序,选择排序,插入排序
  • 秋招面经——快手
  • 【STM32RT-Thread零基础入门】 2. 新建RT-Thread项目
  • 别人直播的时候怎么录屏?分享一些录屏方法
  • React Native 在高IOS版本下无法显示图片的问题处理
  • SSH远程连接MacOS catalina并进行终端颜色配置
  • 用JSON.toJSONString转JSON时,属性的值为null时,输出的JSON里没有该属性
  • Java版企业电子招标采购系统源码—企业战略布局下的采购寻源tbms
  • 轻拍牛头(约数)
  • Vc - Qt - 绘制窗口背景色
  • js和cocos creator学习笔记
  • Ceph分布式存储系统
  • 阿里云SMS,APi接口返回错误码
  • Floyd算法
  • SpringBoot究竟应该如何学习?
  • 为什么很多人认为ChatGPT最好的替代工具是Claude?
  • 学习Vue:简介和优势
  • ***is not a commit and a branch ‘***‘ cannot be created from it 报错
  • QT信号槽连接方式
  • 【yml文件的解释】
  • ChatGPT or BingChat
  • QT 使用第三方库QtXlsx操作Excel表
  • 警惕网络个人技术人员:隐藏代码风险的启示
  • VBA 学习笔记1 对象以及属性
  • netty核心组件以及实现原理
  • 如何正确下载tomcat???
  • mybatis-plus 根据指定字段 批量 删除/修改
  • MQTT宝典
  • 【前端】CSS水平居中的6种方法
  • nginx如何获取真实的ip