unit Unit2;
interface
uses
Classes,activex,SysUtils;
type
tfilecopy = class(TThread)
private
fs,fd:integer;
fsname,fdname:Tfilestream;
{ Private declarations }
protected
procedure Execute;
override;
public
constructor create(sname,dname:Tfilestream;s,d:integer);
end;
implementation
const
buffersize=1024*1024;
constructor tfilecopy.create(sname,dname:Tfilestream;s,d: integer);
begin
fs:=s;
fd:=d;
fsname:=sname;
fdname:=dname;
inherited create(false);
end;
procedure tfilecopy.Execute;
var
n:integer;
buffer
ointer;
begin
CoInitialize(nil);
freeonterminate:=true;
try
fsname.Position:=fs;
fdname.Position:=fs;
if fd>buffersize then
n:=buffersize else
n:=fd;
getmem(buffer,n);
while not Terminated and (fd <> 0)do
begin
if fd > bufferSize then
N := bufferSize else
N := fd;
fsname.Readbuffer(buffer^,n);
fdname.Writebuffer(buffer^,n);
Dec(fd,N);
end;
finally
FreeMem(Buffer,n);
fsname.free;
fdname.free;
end;
CoUninitialize;
end;
end.
上面是我多线程代码
下面是调用方法:
procedure TForm1.Button1Click(Sender: TObject);
begin
if o1.Execute then
//o1是打开对话框控件
begin
o1.Title:='请选择要复制的源文件!' ;
src:=tfilestream.Create(o1.FileName,fmOpenRead );
end;
if o1.Execute then
begin
o1.Title:='请输入目的文件名!' ;
dec:=tfilestream.Create(o1.FileName,fmCreate);
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
i:integer;
n,k,l:integer;
begin
k:=0;
n:=src.Size div sp.Value-1;
L:=src.Size mod sp.Value;//sp 是个控件返回的是一个整型值,控制线程个数的。
for i:=0 to sp.Valuedo
begin
if i=sp.Value then
n:=n+L;
tfilecopy.create(src,dec,k,n);
k:=k+n;
end;
end;
用一个线程是没问题的,现在用多个后报readstream错误。