现在的位置: 首页 > 综合 > 正文

delphi关于线程安全问题

2013年07月08日 ⁄ 综合 ⁄ 共 1328字 ⁄ 字号 评论关闭

TThread提供了几种同步的方法:

 

TThread = class
  protected
     procedure Synchronize(Method: TThreadMethod); overload; //
在继承中调用同步 
 public
    class procedure Synchronize(AThread: TThread; AMethod: TThreadMethod); overload;
    class procedure StaticSynchronize(AThread: TThread; AMethod: TThreadMethod);
 end;


 

OnTerminate事件是线程安全的。

 

TServerSocket

 

TServerSocket的ServerType设置为stThreadBlocking方式时,要注意

       OnAccept: 线程安全

OnGetThread: 线程安全

OnThreadStart : 线程不安全

OnThreadEnd : 线程不安全

OnClientConnect: 线程不安全(好象没被调用)

OnClientDisconnect: 线程不安全

OnClientRead: 线程安全

    OnClientWrite: 线程安全

OnClientError: 线程不安全

 

参考代码:

procedure TServerClientThread.Execute;

begin

  FServerSocket.ThreadStart(Self);

  try

    try

      while True do

      begin

        if StartConnect then ClientExecute;

        if EndConnect then Break;

      end;

    except

      HandleException;

      KeepInCache := False;

    end;

  finally

    FServerSocket.ThreadEnd(Self);

  end;

end;

 

 

procedure TServerClientThread.ClientExecute;

var

  FDSet: TFDSet;

  TimeVal: TTimeVal;

begin

  while not Terminated and ClientSocket.Connected do

  begin

    FD_ZERO(FDSet);

    FD_SET(ClientSocket.SocketHandle, FDSet);

    TimeVal.tv_sec := 0;

    TimeVal.tv_usec := 500;

    if (select(0, @FDSet, nil, nil, @TimeVal) > 0) and not Terminated then

      if ClientSocket.ReceiveBuf(FDSet, -1) = 0 then Break

      else Synchronize(DoRead);

    if (select(0, nil, @FDSet, nil, @TimeVal) > 0) and not Terminated then

      Synchronize(DoWrite);

  end;

end;

 

抱歉!评论已关闭.