多线程写数据库(10分)

  • 主题发起人 主题发起人 Huck
  • 开始时间 开始时间
H

Huck

Unregistered / Unconfirmed
GUEST, unregistred user!
诸位,是不是不能够用两个线程同时往一个数据库中写文件?以下是我的程序
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DB, ADODB, Grids, DBGrids;
type
TForm1 = class(TForm)
DataSource1: TDataSource;
DBGrid1: TDBGrid;
ADOTable1: TADOTable;
Button1: TButton;
Memo1: TMemo;
Button2: TButton;
Memo2: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation
uses unit2,unit3;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
a:Tmythread;
B:Tmythread1;
c:boolean;
begin

c:=true;
a:=Tmythread.Create(c);
b:=Tmythread1.create(c);
a.Resume;
b.Resume;
end;
end.
上面是主程序
下面是两个线程序
unit Unit2;
interface
uses
Classes,SysUtils;
type
Tmythread = class(TThread)
private
{ Private declarations }
protected
procedure Execute;
override;
end;

implementation
uses unit1;
{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure Tmythread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
}
{ Tmythread }
procedure Tmythread.Execute;
var
i:longint;
begin
i:=2;
while i<=1000do
begin
form1.Memo1.Lines.Add(inttostr(i));
with form1.ADOTable1do
begin
disablecontrols;
edit;
appendrecord([inttostr(i)]);
next;
enablecontrols;
end;

i:=i+2;
end;
end;
end.
下面是第二个线程
unit Unit3;
interface
uses
Classes,SysUtils;
type
Tmythread1 = class(TThread)
private
{ Private declarations }
protected
procedure Execute;
override;
end;

implementation
uses unit1;
{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure Tmythread1.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
}
{ Tmythread1 }
procedure Tmythread1.Execute;
var
j:longint;
begin
j:=1;
while j<=1000do
begin
form1.Memo1.Lines.Add(inttostr(j));
with form1.ADOTable1do
begin
disablecontrols;
edit;
appendrecord([inttostr(j)]);
next;
enablecontrols;
end;

j:=j+2;
end;
end;

end.

调试总是出错,能告诉我为什么吗?
 
坦白的说我没有很仔细阅读楼主的程序
两个线程应该不能同时读写同一个数据库(其他文件也是一样)
楼主应该使用线程同步,最简单的方法是使用临界区
 
我看了你的程序,我建议你
1:把form1.Memo1.Lines.Add(inttostr(i));写到一个单独的过程中。同样操作数据库的代码也写到一个单独的过程中,意思是说让线程体来调用他们。
2:在每一个线程体中使用 两个Synchronize对象方法来分别同步化两个过程。
你的代码太长,自己改吧。
还有楼主分是否太少了点?呵 呵。。。。。。。。。。。。。


 
怎样才能利用多线程对数据库进行写数据?我要ADO的
 
后退
顶部