一个简单的 临界区 应用 怎么 不同步..大侠 帮忙看看(有代码)(50分)

  • 主题发起人 主题发起人 令狐小侠
  • 开始时间 开始时间

令狐小侠

Unregistered / Unconfirmed
GUEST, unregistred user!
unit InterLockUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
ListBox1: TListBox;
Button1: TButton;
Button3: TButton;
Button5: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
th1 = class(TThread)
procedure Execute;override;
procedure addtolist;
end;

var
Form1: TForm1;
t1,t2 : th1;
I : integer=0;
implementation
{$R *.dfm}
{ th1 }
procedure th1.addtolist;
begin
form1.ListBox1.Items.Add(inttostr(i));
if form1.ListBox1.Count>0 then
form1.ListBox1.Selected[form1.ListBox1.Count-1] := true;
if form1.ListBox1.Count>1000 then
form1.ListBox1.Clear;
end;

procedure th1.Execute;
var
cs : TRTLCriticalSection;
begin
while not self.Terminateddo
begin
InitializeCriticalSection(CS);
//InterlockedExchangeAdd(i,1);
if tryenterCriticalSection(cs) then
begin
try
inc(i);
self.Synchronize(addtolist);
finally
leaveCriticalSection(cs);
DeleteCriticalSection(CS);
end;
end;
sleep(5);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
t1 := Th1.Create(true);
t2 := th1.Create(true);
button1.Enabled := false;
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
if t1.Suspended then
begin
t1.Resume ;
t2.Resume;
end
else
begin
t1.Suspended := true;
t2.Suspended := true;
end;
end;

procedure TForm1.Button4Click(Sender: TObject);
begin
if t2.Suspended then
t2.Resume
else
t2.Suspended := true;
end;

procedure TForm1.Button5Click(Sender: TObject);
var
j : integer;
begin
for j:= listbox1.ItemIndex to listbox1.Count-2do
begin
if strtoint(listbox1.Items[j])+1
<> strtoint(listbox1.Items[j+1]) then
begin
listbox1.Selected[j+1]:= true;
break;
end;
end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
if listbox1.Count>0 then
listbox1.ItemIndex := 0;
end;

end.
 
怎么连顶的 人都没有啊......
 
.........dfw 没人了??????????
 
帮你顶一个,接个分,顺便发个交流群:
欢迎加入,要收群规,不诚者勿加!长期潜水者勿加!
delphi天堂:4654765
 
不要把什么都写在execute里面,另外用一个方法
 
;> 能同步才怪呢,应该只全局声明一个 cs : TRTLCriticalSection;
所有 thread 都抢(enter/leave)这个 cs 啊
 
已经 解决了.... LSUPER 说的 对...给分 没商量
 

Similar threads

后退
顶部