如何用mutex实现以下代码,谢谢(50分)

  • 主题发起人 主题发起人 true_feiyun
  • 开始时间 开始时间
T

true_feiyun

Unregistered / Unconfirmed
GUEST, unregistred user!
unit Unit831;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
procedure add;
procedure dec;
public
{ Public declarations }
end;

var
Form1: TForm1;
count,num:integer;
good:boolean;
sect:trtlcriticalsection;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.add;
var
i,j:integer;
s:string;
begin
for j:=1 to countdo
begin
if good then
entercriticalsection(sect);
num:=num+10;
i:=num-10;
sleep(5);
s:=format('the value of number is:%d',);
sendmessage(form1.ListBox1.Handle,lb_addstring,0,longint(s));
num:=num-10;
if good then
leavecriticalsection(sect);
end;
end;


procedure TForm1.FormCreate(Sender: TObject);
begin
num:=100;
count:=30;
initializecriticalsection(sect);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
threadid1,threadid2:dword;
begin
good:=false;
listbox1.Clear;
createthread(nil,0,@tform1.add,nil,0,threadid1);
createthread(nil,0,@tform1.dec,nil,0,threadid2);
end;

procedure TForm1.dec;
var
i,j:integer;
s:string;
begin
for j:=1 to countdo
begin
if good then
entercriticalsection(sect);
num:=num-10;
i:=num+10;
sleep(20);
s:=format('the value of number is:%d',);
sendmessage(form1.ListBox1.Handle,lb_addstring,0,longint(s));
num:=num+10;
if good then
leavecriticalsection(sect);
end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
threadid1,threadid2:dword;
begin
good:=true;
listbox1.Clear;
createthread(nil,0,@tform1.add,nil,0,threadid1);
createthread(nil,0,@tform1.dec,nil,0,threadid2);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
deletecriticalsection(sect);
end;

end.
 
哈,简单塞,你创建一个MUTEX,把entercriticalsection(sect)换成拥有MUTEX,在
leavecriticalsection(sect)的时候就 RELEASEMUTEX 放了它塞,你不用了就CLOSEHANDLE
塞,哈互斥和临界区差不多的,但有区别时临界区仅能在进程内,而互斥可以用于跨进程的
哈,还有临界区花的时间比互斥少很多很多,开销小,就这么简单了
 
后退
顶部