CriticalSectionfrm.pas
上传用户:psxgmh
上传日期:2013-04-08
资源大小:15112k
文件大小:2k
源码类别:

Delphi/CppBuilder

开发平台:

Delphi

  1. unit CriticalSectionfrm;
  2. interface
  3. uses
  4.   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  5.   Dialogs, StdCtrls;
  6. type
  7.   //定义一个线程类
  8.   TsyncThread = class(TThread)
  9.   protected
  10.     procedure execute; override;
  11.   end;
  12.   TfrmCriticalSection = class(TForm)
  13.     ListBox1: TListBox;
  14.     btnExecute: TButton;
  15.     ListBox2: TListBox;
  16.     Label1: TLabel;
  17.     Label2: TLabel;
  18.     procedure btnExecuteClick(Sender: TObject);
  19.     procedure FormCreate(Sender: TObject);
  20.     procedure FormDestroy(Sender: TObject);
  21.   private
  22.   //定义线程实例变量
  23.     Thread1, Thread2: TSyncThread;
  24.   //自定义过程,在线程结束时调用
  25.     procedure Thread1Done(sender: TObject);
  26.     procedure Thread2Done(sender: TObject);
  27.     { Private declarations }
  28.   public
  29.     { Public declarations }
  30.   end;
  31. const
  32.   MaxSize = 100;
  33. var
  34.   frmCriticalSection: TfrmCriticalSection;
  35.   //数据全局区
  36.   GlobalData: array[1..MaxSize] of integer;
  37.   IncNum: Integer = 0;
  38.   //定义TRTLCriticalSection类型变量,用于临界区
  39.   CS: TRTLCriticalSection;
  40. implementation
  41. {$R *.dfm}
  42. //线程执行主体
  43. procedure TSyncThread.execute;
  44. var
  45.   i: integer;
  46. begin
  47.   FreeOnTerminate := True;
  48.   //进入临界区
  49.   EnterCriticalSection(CS);
  50.   for i := 1 to Maxsize do
  51.   begin
  52.     Inc(IncNum);
  53.     GlobalData[i] := IncNum;
  54.     Sleep(10);
  55.   end;
  56. end;
  57. //当窗体创建时,初始化临界区
  58. procedure TfrmCriticalSection.FormCreate(Sender: TObject);
  59. begin
  60.   InitializeCriticalSection(CS);
  61. end;
  62. //当窗体释放时,释放临界区
  63. procedure TfrmCriticalSection.FormDestroy(Sender: TObject);
  64. begin
  65.   DeleteCriticalSection(CS);
  66. end;
  67. //创建线程实例
  68. procedure TfrmCriticalSection.btnExecuteClick(Sender: TObject);
  69. begin
  70.   Thread1 := TSyncThread.Create(false);
  71.   Thread1.OnTerminate := Thread1Done;
  72.   Thread2 := TSyncThread.Create(false);
  73.   Thread2.OnTerminate := Thread2Done;
  74. end;
  75. //当线程1执行完后,将GlobalData数据显示出来
  76. procedure TfrmCriticalSection.Thread1Done(sender: TObject);
  77. var
  78.   i: integer;
  79. begin
  80.   ListBox1.Items.Clear;
  81.   for i := 1 to MaxSize do
  82.     Listbox1.Items.Add(intToStr(GlobalData[i]));
  83.   //离开临界区
  84.   LeaveCriticalSection(CS);
  85. end;
  86. //当线程2执行完后,将GlobalData数据显示出来
  87. procedure TfrmCriticalSection.Thread2Done(sender: TObject);
  88. var
  89.   i: integer;
  90. begin
  91.   ListBox2.Items.Clear;
  92.   for i := 1 to MaxSize do
  93.     Listbox2.Items.Add(intToStr(GlobalData[i]));
  94.   //离开临界区
  95.   LeaveCriticalSection(CS);
  96. end;
  97. end.