将对象分配给另一个线程

时间:2015-10-17 18:21:53

标签: multithreading delphi locking delphi-10-seattle

我有多线程应用程序,我有一个关于在线程之间分配对象以及如何正确锁定它们的问题。

我定义了自定义类型类,在主线程中我创建了该类型的实例。我想为一个线程分配不同的对象,这些对象将在一个线程的Execute方法中使用。

type TMyClass = class
private
  FData: Integer;
public
  property Data: Integer read FData write FData;
end;

TMyThread = class(TThread)
private 
  FMyObject: TMyObject;
  FLock: TCriticalSection;

protected 
  procedure Execute; override;
public
  procedure Lock;
  procedure Unlock;
  property MyObject: TMyObject read FMyObject write FMyObject;
end;

procedure TMyThread.Lock;
begin
  FLock.Acquire;
end;

procedure TMyThread.Unlock;
begin
  FLock.Release;
end;

procedure TMyThread.Execute; 
begin

  while not Terminated do
  begin
    Lock;
    try
      if Assigned(FMyObject) then 
        FMyObject.Data := FMyObject.Data + 1;
    finally
      Unlock;
    end;
  end;
end;


from main thread:

var MyObject1, MyObject2: TMyObject;
    thOperation: TMyThread;
    CurrData1, CurrData2: Integer;

begin
  // create two objects
  MyObject1 := TMyObject.Create;
  MyObject2 := TMyObject.Create;

  // create thread(started)
  thOperation := TMyThread.Create(false);

  thOperation.Lock;
  try
    thOperation.MyObject := MyObject1;
  finally
    thOperation.Unlock;
  end;

  /// .... do some stuff in main thread
  thOperation.Lock;
  try
    CurrData1 := thOperation.MyObject.Data;
  finally
    Unlock;
  end;

  // let's assign new object on a running thread
  thOperation.Lock;
  try
    thOperation.MyObject := MyObject2;
  finally
    thOperation.Unlock;
  end;

  /// .... do some stuff in main thread again
  thOperation.Lock;
  try
    CurrData2 := thOperation.MyObject.Data;
  finally
    Unlock;
  end;


  if CurrData1 <> CurrData2 then ShowMessage('Different result!');


  // do cleanup
  thOperation.Terminate;
  thOperation.WaitFor;
  thOperation.Free;

  MyObject1.Free;
  MyObject2.Free;


end;

在为线程分配不同的对象时,这种锁定方法是否正确?

1 个答案:

答案 0 :(得分:1)

要回答您的问题,是的,您使用TCriticalSection的方法还可以。

有关多线程的更多信息,如果你还没有,那么谷歌将采用Martin Harvey的“多线程 - Delphi方式”。一篇优秀的文章(或者我应该说是书)。