如何在操作某一资源的时候禁止别的代码进行任何操作,直到这一操作过完成(如:数组资源)(50分)

  • 主题发起人 主题发起人 sungirl1126
  • 开始时间 开始时间
S

sungirl1126

Unregistered / Unconfirmed
GUEST, unregistred user!
我知道有一种锁是对代码时行锁定。可不可以对资源(数组)进行锁定。最好能用代码说明。
 
http://www.5xsoft.com/data/200104/2723381401.htm
 
在程序内部可以使用同步处理。
 
那个贴子我看了,不知如何用啊,能不能写成代码给发过来。马一发分
sungirl1126@21cn.com。
 
就用那个帖子的 TMutex 啊
Mutex := TMutex.Create(nil, false, 'Array');
if wrSignaled = Mutex.WaitFor(10000) then
//若获得互斥对象的拥有权
begin

try
  //操作数组
finally
Mutex.Release;//释放对互斥对象的拥有权
end;

end;
 
参考此例子
unit ThreadsynchronizatUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
var
counter : Integer;
criticalsection : TRTLCriticalSection;
type
TCounter = class(TThread)
private
{ Private declarations }
FLabel:TLabel;
FNumber:integer;
FIdx:integer;
procedure PushTheButton;
protected
Procedure Execute;Override;
public
{ Public declarations }
Constructor Create;
end;

TForm1 = class(TForm)
Timer1: TTimer;
Timer2: TTimer;
Button2: TButton;
Edit3: TEdit;
Button1: TButton;
Memo1: TMemo;
procedure Timer1Timer(Sender: TObject);
procedure Timer2Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure ThreadaDone(Sender : TObject);
public
{ Public declarations }
a,b : TCounter;
end;

var
Form1: TForm1;
implementation
{$R *.dfm}
constructor TCounter.create;
begin
inherited Create(False);
FreeOnTerminate:=True;
end;

procedure TCounter.execute;
var
i:integer;
begin
EnterCriticalSection(criticalsection);
try
for i:=1 to 10do
begin
sleep(100);
counter := i;
Synchronize(PushTheButton);

end;
finally
LeaveCriticalSection(criticalsection);
end;
end;

procedure TCounter.PushTheButton;
begin
Form1.Memo1.Lines.Add(IntToStr(counter));
showmessage(IntToStr(counter));
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
if DateTimeToStr(now)=edit3.text then
begin
a:=TCounter.create;
a.OnTerminate:=ThreadaDone;
end;
end;

procedure TForm1.Timer2Timer(Sender: TObject);
begin
if DateTimeToStr(now)=edit3.text then
begin
b:=TCounter.create;
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
edit3.Text:=DateTimeToStr(now+0.00002);
end;

Procedure TForm1.ThreadaDone;
begin

end;

procedure TForm1.Button1Click(Sender: TObject);
begin
begin
a:=TCounter.create;
a.OnTerminate:=ThreadaDone;
end;
end;

initialization
InitializeCriticalSection(criticalsection);
finalization
DeleteCriticalSection(criticalsection);
end.

 
多人接受答案了。
 
后退
顶部