delphi 怎么实现多线程的同步
发布网友
发布时间:2022-04-30 23:54
我来回答
共1个回答
热心网友
时间:2022-06-20 20:53
多线程同步
"临界区"(CriticalSection): 当把一段代码放入一个临界区, 线程执行到临界区时就独占了, 让其他也要执行此代码的线程先等等;
使用格式如下:
var CS: TRTLCriticalSection; {声明一个 TRTLCriticalSection 结构类型变量; 它应该是全局的}
InitializeCriticalSection(CS); {初始化}
EnterCriticalSection(CS); {开始: 轮到我了其他线程走开}
LeaveCriticalSection(CS); {结束: 其他线程可以来了}
DeleteCriticalSection(CS); {删除: 注意不能过早删除}
多线程同步示例
1 unit Unit1;
2
3 interface
4
5 uses
6 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
7 Dialogs, StdCtrls;
8
9 type
10 TForm1 = class(TForm)
11 ListBox1: TListBox;
12 Button1: TButton;
13 procere FormCreate(Sender: TObject);
14 procere FormDestroy(Sender: TObject);
15 procere Button1Click(Sender: TObject);
16 end;
17
18 var
19 Form1: TForm1;
20
21 implementation
22
23 {$R *.dfm}
24
25 var
26 CS: TRTLCriticalSection;
27
28 function MyThreadFun(p: Pointer): DWORD; stdcall;
29 var
30 i: Integer;
31 begin
32 EnterCriticalSection(CS);
33 for i := 0 to 99 do Form1.ListBox1.Items.Add(IntToStr(i));
34 LeaveCriticalSection(CS);
35 Result := 0;
36 end;
37
38 procere TForm1.Button1Click(Sender: TObject);
39 var
40 ID: DWORD;
41 begin
42 CreateThread(nil, 0, @MyThreadFun, nil, 0, ID);
43 CreateThread(nil, 0, @MyThreadFun, nil, 0, ID);
44 CreateThread(nil, 0, @MyThreadFun, nil, 0, ID);
45 end;
46
47 procere TForm1.FormCreate(Sender: TObject);
48 begin
49 ListBox1.Align := alLeft;
50 InitializeCriticalSection(CS);
51 end;
52
53 procere TForm1.FormDestroy(Sender: TObject);
54 begin
55 DeleteCriticalSection(CS);
56 end;
57
58 end.