当前位置:编程学习 > Delphi >>

delphi 线程同步 临界区

dephi线程的同步,最简单的就是临界区。
临界区的意思就是,一次只能由一个线程执行的代码。
 
在使用临界区之前,必须使用InitializeCriticalSection( )过程来初始化它。
其声明如下:
procedure InitializeCriticalSection(var lpCriticalSection);stdcall;
 
lpCriticalSection参数是一个TRTLCriticalSection类型的记录,并且是变参。至于TRTLCriticalSection
是如何定义的,这并不重要,因为很少需要查看这个记录中的具体内容。只需要在lpCriticalSection中传
递未初始化的记录,InitializeCriticalSection()过程就会填充这个记录.
 
在记录被填充后,我们就可以开始创建临界区了。这时我们需要用 E n t e r C r i t i c a l S e c t i o n ( )和L e a v e C r i t i c a l S e c t i o n ( )来封装代码块.
当你不需要T RT L C r i t i c a l S e c t i o n记录时,应当调用D e l e t e C r i t i c a l S e c t i o n ( )过程,下面是它的声明:
procedure DeleteCriticalSection(var lpCriticalSection: TRT L C r i t i c a l S e c t i o n ) ; s t d c a l l ;
 
列子:
[delphi] 
unit CriticaSection;  
  
interface  
  
uses  
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,  
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;  
  
type  
  TForm2 = class(TForm)  
    btn1: TButton;  
    lstbox1: TListBox;  
    procedure btn1Click(Sender: TObject);  
  public  
    procedure ThreadsDone(Sender : TObject);  
  end;  
  
  TFooThread=class(TThread)  
    protected  
      procedure Execute;override;  
  end;  
  
var  
  Form2: TForm2;  
  
implementation  
  
{$R *.dfm}  
const  
  MAXSIZE=128;  
var  
  NextNumber : Integer=0;  
  DoneFlags : Integer=0;  
  GlobalArray : array[1..MAXSIZE] of Integer;  
  CS : TRTLCriticalSection;  
function GetNextNumber:Integer;  
begin  
  Result:=NextNumber;  
  Inc(nextnumber);  
end;  
  
{ TForm2 }  
  
procedure TForm2.btn1Click(Sender: TObject);  
begin  
 // InitializeCriticalSection(CS);  
  TFooThread.Create(False);  
  TFooThread.Create(False);  
end;  
  
procedure TForm2.ThreadsDone(Sender: TObject);  
var  
  i:Integer;  
begin  
  Inc(DoneFlags);  
  if DoneFlags=2 then  
  for I := 1 to MAXSIZE do  
    lstbox1.Items.Add(IntToStr(GlobalArray[i]));  
  DeleteCriticalSection(CS);  
end;  
  
{ TFooThread }  
  
procedure TFooThread.Execute;  
var  
  i:Integer;  
begin  
  EnterCriticalSection(cs);  
  OnTerminate:=Form2.ThreadsDone;  
  for I := 1 to MAXSIZE do  
  begin  www.zzzyk.com
    GlobalArray[i]:=GetNextNumber;  
  end;  
  LeaveCriticalSection(CS);  
end;  
  
end.  
 
这样就可以是线程同步,不会发生冲突。
 
补充:软件开发 , Delphi ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,