字符串线程安全问题

cdhuanglei 2006-09-23 11:11:39
我用一个字符串变量(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;
...全文
193 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
cdhuanglei 2006-09-26
  • 打赏
  • 举报
回复
呵呵,高手们都哪去了?
dashi 2006-09-25
  • 打赏
  • 举报
回复
接分~
日总是我哥 2006-09-23
  • 打赏
  • 举报
回复
我顶你个肺~
ly_liuyang 2006-09-23
  • 打赏
  • 举报
回复
用临界区~
Win32API
自己看Help去

830

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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