如何制作多线程复制文件 [英] how to make a multithread copy files

查看:16
本文介绍了如何制作多线程复制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个文件中复制多个文件,但是使用多线程,假设文件A是不同线程复制数据的文件,在这种情况下,每个线程都意味着复制文件A中的一个文件,使用以下过程:

I want to copy many files in one, but using multiThread,supposing that file A is the file in which different threads copy datas, in this case each thread is meant to copy one file in file A, using this procedure:

procedure ConcatenateFiles(const InFileNames: array of string;
const OutFileName: string);
var
i: Integer;
InStream, OutStream: TFileStream;
begin
OutStream := TFileStream.Create(OutFileName, fmCreate);
try
 for i := 0 to high(InFileNames) do
 begin
  InStream := TFileStream.Create(InFileNames[i], fmOpenRead);
  try
    OutStream.CopyFrom(InStream, InStream.Size);
  finally
    InStream.Free;
  end;
 end;
finally
 OutStream.Free;
end;

结束;

首先,在这种情况下是否可以实现多线程复制文件,因为OutFileName是一个全局变量,两个线程不能同时使用它,这是我得到的错误,如果这是可能的,我如何同步线程以避免同时多个进程使用 OutFileName?而且制作多线程复制文件真的有效率吗,我说的是复制文件的速度.感谢您的回复

First, is it possible to realise multithread copy files in this case, because OutFileName is a global variable, two threads can't use it at the same time, and this is the error that i get, if this is possible how can I synchronise threads to avoid the use of OutFileName by more than one processus in a moment? And is it really efficient to make a multithread copy files, I'm talking about the speed of copying files. thanks for your replies

推荐答案

完全可以使用多线程复制文件.您通常会使用单个生产者线程和多个消费者来完成工作.在您的情况下,您正在连接.因此,您需要计算出每个源文件的起点和终点,然后让线程在预先计算的位置写入目标文件的单独部分.当然可以.

It's perfectly possible to copy files using multiple threads. You would typically use a single producer thread and multiple consumers to do the work. In your case you are concatenating. So you'd need to work out the start and end point of each source file, and then get the threads to write separate parts of the destination file at the pre-calculated positions. Certainly possible.

但是,这不是一个好主意.当作业受 CPU 限制时,多线程运行良好.文件复制受磁盘限制,没有多少额外的线程可以提供帮助.事实上,您最终可能会使性能变得更糟,因为多个线程会在争夺共享磁盘资源的同时相互干扰.

However, it's not a good idea idea. Multiple threading works well when the job is CPU bound. File copying is disk bound and no amount of extra threads can help. In fact you will likely end up making performance worse because the multiple threads will just get in each others way whilst fighting over the shared disk resource.

这篇关于如何制作多线程复制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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