高手求救,线程同步问题

seward 2007-11-29 04:46:49
俺一直搞的是java,初写dephi程序。但不知,dephi的线程同步怎么做。 在java里用关键字synchronized就搞定的。dephi是否也有同类方法,还望高手赐教。

以下是我定义的一个对象。 我希望TMsgList同步,一个线程在putMsg的时候,其它线程不能执行removeMsg,

TMsgList = class(TStringList)
//------------------消息队列函数-------------------------------------
procedure putMsg(sequence:LongInt;var bs:array of char;buffsize:integer);
procedure removeMsg(sequence:LongInt);
end;
...全文
36 点赞 收藏 3
写回复
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
liangpei2008 2007-11-29
用事件或临界区~
事件楼上大哥已说
TMsgList = class(TStringList)
//------------------消息队列函数-------------------------------------
procedure putMsg(sequence:LongInt;var bs:array of char;buffsize:integer);
procedure removeMsg(sequence:LongInt);
public
Constructor Create;
.......
end;
use
SyncObjs;


TEnhancedCriticalSection = class(TCriticalSection)
public
function TryEnter: boolean;
end;

var
Msg: TEnhancedCriticalSection;

begin
MsgList.Create
try
if ( Msg.TryEnter) then
finally
Msg.Release;
end;
end;
大概就是这个意思~
回复
sdzeng 2007-11-29
最简单的是从TThreadList继承你的TMsgList
回复
oushengfen 2007-11-29
很多方法,给你一个事件方法

unit Unit1;

interface

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

type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
EventHandle: THandle; {事件句柄}
ThreadHandle: THandle; {线程句柄}
implementation

{$R *.DFM}

function ThreadFunction(Info: Pointer): Integer; stdcall;
var
FormDC: HDC;
Counter: Integer;
CounterStr: string;
ObjRtn: Integer;
begin
ObjRtn := WaitForSingleObject(EventHandle, INFINITE);
FormDC := GetDC(Form1.Handle);
for Counter := 1 to 100000 do
begin
CounterStr := IntToStr(Counter);
TextOut(FormDC, 10, 10, PChar(CounterStr), Length(CounterStr));
Application.ProcessMessages;
ObjRtn := WaitForSingleObject(EventHandle, INFINITE);
end;
ReleaseDC(Form1.Handle, FormDC);
ExitThread(4);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
ThreadID: Dword;
begin
ThreadHandle := CreateThread(nil, 0, @ThreadFunction, nil, 0, ThreadId);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
SetEvent(EventHandle);
Label1.Caption := 'Event is signaled';
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
ResetEvent(EventHandle);
Label1.Caption := 'Event is non signaled';
end;

procedure TForm1.Button4Click(Sender: TObject);
begin
PulseEvent(EventHandle);
Label1.Caption := 'signaled/nonsignaled';
end;

procedure TForm1.Button5Click(Sender: TObject);
begin
EventHandle := CreateEvent(nil, True, False, 'MyEvent');
end;

end.
回复
发动态
发帖子
网络通信/分布式开发
创建于2007-08-02

1565

社区成员

Delphi 网络通信/分布式开发
申请成为版主
社区公告
暂无公告