线程同步问题 请帮忙(100分)

  • 主题发起人 主题发起人 tscc
  • 开始时间 开始时间
T

tscc

Unregistered / Unconfirmed
GUEST, unregistred user!
我正在写一个多线程udp通讯的程序,由于刚接触不太熟悉,写了一个测试程序,总出错,不知何故请高手指教
程序如下:请千万别嫌长,帮忙看看
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StrUtils,IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer,IdSocketHandle,
StdCtrls,Contnrs,SyncObjs;
type
TForm1 = class(TForm)
IdUDPServer1: TIdUDPServer;
Memo1: TMemo;
Memo2: TMemo;
Memo3: TMemo;
procedure IdUDPServer1UDPRead(Sender: TObject;
AData: TStream;
ABinding: TIdSocketHandle);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
datathread = class(TThread) { 声明线程类 }
private
protected
procedure ddd;
procedure Execute;
override;{ 执行线程的方法 }
public
constructor Create();
virtual;
{ 线程构造器 }
end;
var
Form1: TForm1;
//MyQueue:TQueue;
//声明队变量
//zhi:^integer;
// cs:trtlcriticalsection;
rcs:TCriticalSection;
gcount:integer;
mcount:integer;
implementation
{$R *.dfm}
procedure datathread.ddd;
begin
form1.Memo1.Lines.Append(inttostr(gcount)+':'+inttostr(mcount));
end;
procedure datathread.Execute;
begin
{ Place thread code here }
try
FreeOnTerminate:=True;
while not Terminateddo
begin
//entercriticalsection(cs);
rcs.Enter;
try
if gcount >0 then
dec(gcount);
finally
//leavecriticalsection(cs);
rcs.leave;
end;
synchronize(ddd);
sleep(5);
end;
except
showmessage('threaderror');
end;
end;
constructor datathread.Create();
begin
inherited Create(False);
FreeOnTerminate := True;
end;
procedure TForm1.IdUDPServer1UDPRead(Sender: TObject;
AData: TStream;
ABinding: TIdSocketHandle);
var
DataStringStream: TStringStream;
str:string;
begin
DataStringStream := TStringStream.Create('');
try
DataStringStream.CopyFrom(AData, AData.Size);
str:= DataStringStream.DataString;
if leftstr(str,1)='0'
then
sleep(2)//memo2.Lines.Add(str)
else
if leftstr(str,1)='1'
then
sleep(2)//memo3.Lines.Add(str)
else
begin
//entercriticalsection(cs);
rcs.Enter;
try
inc(gcount);
inc(mcount);
finally
//leavecriticalsection(cs);
rcs.Leave;
end;
end;

finally
DataStringStream.Free;
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
gcount:=0;
mcount:=0;
//initializecriticalsection(cs);
rcs:=Tcriticalsection.Create;
idudpserver1.Active:=true;
datathread.Create();
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
//deletecriticalsection(cs);
rcs.Destroy;
end;
end.
在程序退出时错误提示:
project project_1.exe raised exception class EaccessViolation
with message'Access violation at address 004594A3 in module 'project1.exe'.Read of address 00000220'.process stopped.Use Step or Run to contionuel
 
呵呵,没仔细研究.
但无论问题是不是出在这里,都要注意,请使用Free方法释放对象,而不是Destroy.
 
try:
FormDestroy --------> FormClose
 
to leechange
改成free 也不行,是不是与客户端发送数据频率和数据处理线程中的延时有关
 
在关闭窗体前,先关闭UDPServer试试.
 
以上都不行啊,真急死人了
 
你把程序发给我,我帮你解决 li_jiheng@yahoo.com.cn
 
接受答案了.
 
在rcs.Destroy前加一个rcs.leave;
 
后退
顶部