请问Delphi中如何进行多线程的编程呀,如何同步?

DentistryDoctor 2004-08-20 04:57:59
RT
...全文
294 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Billy_Chen28 2004-08-20
  • 打赏
  • 举报
回复
原来楼上的可以同时给三个答案啊:)
不过除了第一个答案,后面两个答案好像都必须花钱买书:)
因为只有第一本书才有电子版的:)
solokey 2004-08-20
  • 打赏
  • 举报
回复
我的回答很简单。delphi5开发人员指南第11章,delphi Win32核心API参考第6章,delphi技术手册第4章
Billy_Chen28 2004-08-20
  • 打赏
  • 举报
回复
创建多线程程序并且同步线程,我们需要首先理解一些东西,比如临界区和互斥等概念,楼主可查相关基础资料得到这些,在DLEPHI中我们要用到与临界区和互斥相关的函数如下:
EnterCriticalSection()
LeaveCriticalSection()
DeleteCriticalSection()
InitializeCriticalSection()等等,
举一个例子下如:

unit Main;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;

type
TMainForm = class(TForm)
Button1: TButton;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
private
procedure ThreadsDone(Sender: TObject);
end;

TFooThread = class(TThread)
protected
procedure Execute; override;
end;

var
MainForm: TMainForm;

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; // return global var
inc(NextNumber); // inc global var
end;

procedure TFooThread.Execute;
var
i: Integer;
begin
OnTerminate := MainForm.ThreadsDone;
EnterCriticalSection(CS); // CS begins here
for i := 1 to MaxSize do
begin
GlobalArray[i] := GetNextNumber; // set array element
Sleep(5); // let thread intertwine
end;
LeaveCriticalSection(CS); // CS ends here
end;

procedure TMainForm.ThreadsDone(Sender: TObject);
var
i: Integer;
begin
inc(DoneFlags);
if DoneFlags = 2 then
begin // make sure both threads finished
for i := 1 to MaxSize do
{ fill listbox with array contents }
Listbox1.Items.Add(IntToStr(GlobalArray[i]));
DeleteCriticalSection(CS);
end;
end;

procedure TMainForm.Button1Click(Sender: TObject);
begin
InitializeCriticalSection(CS);
TFooThread.Create(False); // create threads
TFooThread.Create(False);
end;

end.

5,927

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧