字符串线程安全问题
我用一个字符串变量(MsgRecvPool)来存放从Socket接收到的报文,然后用一个线程专门来分析与截取里面的内容。Socket不断的把数据加到MsgRecvPool的后面,而线程也不断的析取MsgRecvPool中的内容,请问如果实现对MsgRecvPool的线程安全访问?
{报文提取线程类}
TParseThread = class(TThread)
private
protected
procedure Execute; override;
public
constructor Create;
end;
var
MsgRecvPool: string; //Socket报文接收缓冲
ParseThread: TParseThread; //报文提取线程
procedure TForm1.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
begin
MsgRecvPool := MsgRecvPool + Socket.ReceiveText; //把接收的报文加到MsgRecvPool后面
if ParseThread.Suspended then ParseThread.Resume; //如果分析线程被挂起,则唤醒它
end;
procedure TParseThread.Execute;
var
HeadPos, FootPos, MsgLength: integer;
AMsg: string;
begin
while not Terminated do
begin
MsgLength := Length(MsgRecvPool);
if MsgLength = 0 then //如果MsgRecvPool中为空则挂起线程
begin
Suspend;
Continue;
end;
HeadPos := SmartPos('<?xml ', MsgRecvPool, False);
if HeadPos > 0 then
begin
FootPos := Pos('</Msg>', MsgRecvPool);
if FootPos > 0 then
begin
AMsg := Copy(MsgRecvPool, HeadPos, FootPos - Headpos + 7); //取得一段完整报文
Delete(MsgRecvPool, 1, FootPos + 6); //从MsgRecvPool中清除已取得的报文
Synchronize(InvokeMsgProcessor);
end
end
else MsgRecvPool := ''; // HeadPos <= 0 缓冲中没有报文头,则抛弃已缓冲内容
Sleep(0);
end;
end;