我设计思路:主程序中用comport的OnRxChar事件来接收串口的数据,并将它存在strlist中,使用一个线程专门处理strlist中的数据。现在出现的问题是在程序执行一段时间后在***行出现错误,提示原因为“access violation at address 00619B8C in module ,Read of address 00000000”,发现该行strlist:=nil;试问我在程序创建时就已经进行strlist.creat(),并未对其进行销毁,怎么strlist:=nil??是因为多线程同步所引起?该怎么解决//主框架创建
procedure TFrm_Main.FormCreate(Sender: TObject);
begin
...
strlist:=Tstringlist.Create; //创建用于存储串口接收数据包的二级缓存
strlist.Sorted:=false;
...
end;//主程序中串口接收字符,其中strlist为TStringlist
procedure TFrm_Main.Comm1RxChar(Sender: TObject; Count: Integer);
var str:string;
begin
comm1.ReadStr(Str,Count);
EnterCriticalSection(cs1);
strlist.Add(Str);
LeaveCriticalSection(cs1);
end;//线程执行代码
procedure ReceiveThread.Execute;
var str:string;
i,icount:integer;
Tcs:TRTLCriticalSection;
begin
i:=0;
InitializeCriticalSection(Tcs);
while not terminated do
begin
if Frm_Main.strlist.Count>0 then ************************出错
begin
EnterCriticalSection(Tcs);
str:= Frm_Main.strlist.Strings[0];
Frm_Main.strlist.Delete(0);
LeaveCriticalSection(Tcs);
Frm_Main.ProcessRecStr(str); //处理函数,该函数未用到strlist
end
else
begin
sleep(1000);
end ;
end;
end;
procedure TFrm_Main.FormCreate(Sender: TObject);
begin
...
strlist:=Tstringlist.Create; //创建用于存储串口接收数据包的二级缓存
strlist.Sorted:=false;
...
end;//主程序中串口接收字符,其中strlist为TStringlist
procedure TFrm_Main.Comm1RxChar(Sender: TObject; Count: Integer);
var str:string;
begin
comm1.ReadStr(Str,Count);
EnterCriticalSection(cs1);
strlist.Add(Str);
LeaveCriticalSection(cs1);
end;//线程执行代码
procedure ReceiveThread.Execute;
var str:string;
i,icount:integer;
Tcs:TRTLCriticalSection;
begin
i:=0;
InitializeCriticalSection(Tcs);
while not terminated do
begin
if Frm_Main.strlist.Count>0 then ************************出错
begin
EnterCriticalSection(Tcs);
str:= Frm_Main.strlist.Strings[0];
Frm_Main.strlist.Delete(0);
LeaveCriticalSection(Tcs);
Frm_Main.ProcessRecStr(str); //处理函数,该函数未用到strlist
end
else
begin
sleep(1000);
end ;
end;
end;
难道在Frm_Main.strlist.Count>0前后还要加上?不是说只是写的时候需要保护,读的时候可以不需要的吗
难道在Frm_Main.strlist.Count>0前后还要加上?不是说只是写的时候需要保护,读的时候可以不需要的吗
---------------------------------------------------------
TstringList不是一个简单的全局变量。不是写的时候需要保护,读的时候不需要。
而且,你在线程内用的EnterCriticalSection(Tcs)
为什么在主线程中使用EnterCriticalSection(cs1)
可还是出现同样的错误
------------------------------------------------------------
如果不能直接使用,那该怎么进行间接使用?
TStringList在我的代码中纯粹是个缓存区
------------------------------------------------------------
如果不能直接使用,那该怎么进行间接使用?
TStringList在我的代码中纯粹是个缓存区