多个线程可以同时将数据写入一个文件吗? [英] Can multiple threads write data into a file at the same time?

查看:60
本文介绍了多个线程可以同时将数据写入一个文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你用过p2p下载软件,他们可以用多线程下载一个文件,而且他们只创建了一个文件,所以我想知道线程如何将数据写入该文件.顺序还是并行?

If you have ever used a p2p downloading software, they can download a file with multi-threading, and they created only one file, So I wonder how the threads write data into that file. Sequentially or in parallel?

想象一下,您想将一个大数据库表转储到一个文件中,以及如何使这项工作更快?

Imagine that you want to dump a big database table to a file, and how to make this job faster?

推荐答案

您可以使用多个线程将 a 写入文件,例如一个日志文件.但是你必须像@Thilo 指出的那样协调你的线程.您需要同步文件访问并只写入整个记录/行,或者您需要有一个将文件区域分配给不同线程的策略,例如使用已知偏移量和大小重新构建文件.

You can use multiple threads writing a to a file e.g. a log file. but you have to co-ordinate your threads as @Thilo points out. Either you need to synchronize file access and only write whole record/lines, or you need to have a strategy for allocating regions of the file to different threads e.g. re-building a file with known offsets and sizes.

出于性能原因很少这样做,因为大多数磁盘子系统在顺序写入时性能最佳,而磁盘 IO 是瓶颈.如果创建记录或文本行(或网络 IO)的 CPU 是瓶颈,它可以提供帮助.

This is rarely done for performance reasons as most disk subsystems perform best when being written to sequentially and disk IO is the bottleneck. If CPU to create the record or line of text (or network IO) is the bottleneck it can help.

您想将大数据库表转储到文件的图像,以及如何使这项工作更快?

Image that you want to dump a big database table to a file, and how to make this job faster?

按顺序编写可能是最快的.

Writing it sequentially is likely to be the fastest.

这篇关于多个线程可以同时将数据写入一个文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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