一个使用多线程写同一个文件的程序示例,请大家帮忙调试

sodme 2003-08-29 01:16:37
//程序很简单,内容如下:


unit Main_Unit;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type TWriteThread = class(TThread)

private
//
protected
procedure Execute;
public
//
end;

type
TMainForm = class(TForm)
Button1: TButton;
Button2: TButton;
CheckBox1: TCheckBox;
Memo1: TMemo;
procedure Button2Click(Sender: TObject);

private
{ Private declarations }
public
{ Public declarations }
procedure ThreadDone(Sender : TObject);
end;

var
MainForm: TMainForm;
DoneFlags : integer;
tempfile : file;
cs:TRTLCriticalSection;
filename : string;
pos : longint;

implementation

{$R *.dfm}

{ TWriteThread }

{constructor TWriteThread.create;
begin
//
end; }

procedure TWriteThread.Execute; //每个线程都向today.txt写入内容:"f"
var
i ,temp_len : integer;
buf : array[1..100] of char;
begin
OnTerminate:=MainForm.ThreadDone;
EnterCriticalSection(cs);
filename := 'D:\Documents and Settings\Administrator\桌面\today.txt';
for i:=1 to 100 do
begin
assignfile(tempfile,filename);
if FileExists(filename)=true then
begin
reset(tempfile,1);
pos:=filesize(tempfile);
end
else
begin
rewrite(tempfile,1);
pos:=0;
end;
seek(tempfile,pos);

FillChar(buf,sizeof(buf),'f');
temp_len := sizeof(buf);
blockwrite(tempfile,buf,temp_len);
end;
LeaveCriticalSection(cs);
end;

{ TMainForm }

procedure TMainForm.ThreadDone;
var
i : integer;
begin
//inherited;
inc(DoneFlags);
if DoneFlags = 10 then
begin //make sure 10 threads all finished
closefile(tempfile);
DeleteCriticalSection(cs);
end
end;

procedure TMainForm.Button2Click(Sender: TObject);
var
TempWriteThds: array[1..10] of TWriteThread;
i : integer;
Handel_Thd : array[1..10] of THandle;
begin
InitializeCriticalSection(cs);
for i:=1 to 10 do //创建十个线程
begin
TempWriteThds[i] :=TWriteThread.Create(false);
sleep(10);
Handel_Thd[i] := TempWriteThds[i].Handle;
end;
end;

end.



我在运行时,出现:Abstract error!请大家帮忙看一下是什么问题。谢谢!
...全文
155 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
「已注销」 2003-08-30
  • 打赏
  • 举报
回复
mme(dog) ,你所说的分割是什么意思?你是指分块下载吗?可否交流一下你的源代码,我的邮箱:upup_day@hotmail.com。如果你想要我的源代码交流,也可以,不过,我还没有完全实现。
mme 2003-08-29
  • 打赏
  • 举报
回复
呵呵,这么巧,我也是用多线程传输文件来测试下载速度的.

不知道是什么原因,发现如果用分割文件的方式来传送,速度比单写一个文件快很多....
「已注销」 2003-08-29
  • 打赏
  • 举报
回复
呵呵,我这并不是专门为了多线程写文件而写的多线程程序,是多线程下载中的一段测试代码。
mme 2003-08-29
  • 打赏
  • 举报
回复
呵呵,其实多线程写文件真的很简单的

只要在线程里面FileSeek到自己的位置,然后就开始写.不会出什么问题的.

不过我试验发现其实多线程写大文件并不能快多少的.可能反而会慢很多.
「已注销」 2003-08-29
  • 打赏
  • 举报
回复
郁闷!问题刚贴出来,自己就解决了。:( 浪费了100分。

1,594

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 网络通信/分布式开发
社区管理员
  • 网络通信/分布式开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧