Delphi创建线程安全的编写函数

我正在使用Delphi XE来创建多线程应用程序。

我想创建一个线程来处理所有写入firebird / sqlite数据库日志的操作。
我想创建几个可以完成某些工作的线程,而其他一些线程则需要在需要时使用写入日志线程。

Thread1 = writing log thread  
Thread2 = do some math and from time to time use Thread1 to write log.  
Thread3 = do some other stuff and from time to time use Thread1 to write log.  

以此类推

为简单起见,我在线程1中创建了一个名为WriteCollectionLog的方法,所有其他线程都需要使用该方法将日志写入线程1内存(一个集合),线程1“ onexecute”将处理将实际日志写入数据库的过程。该方法旨在像“抛物线”方法一样使用。

现在如何使该线程安全?还是可以使其线程安全? (通过使用TCriticalSection吗?)

thread2.WriteCollectionLog ...
thread3.WriteCollectionLog ...

procedure Thread1.WriteCollectionLog(aIDWORKFLOW : Integer);
var workItem : TLogFIREBIRD_Item;
begin
  try
    readWriteCriticalSection.Acquire;  <--- this will suspend the calling thread .. like thread2,thread3 and not the thread1?
    do stuff;
  finally
    readWriteCriticalSection.Release;
  end;
end;

致谢
拉兹万

qqq279985481 回答:Delphi创建线程安全的编写函数

只需实现您编写的内容:仅从Thread1写入DB。

请不要期望从另一个线程“调用”一个线程,因为您可能会使用“同步”在主线程中运行一些代码。我想这会阻塞,这不是您所期望的。

这个想法是要有一个小的内存结构,在线程之间共享,并由关键部分保护。一个目标是使任何关键部分尽可能小。

例如,您可以使用TObjectQueue,然后Thread2和Thread3会将一些数据推送到队列中,而Thread1将等待队列中的一些待处理数据,然后将其取消排队并写入-如果您定义一个事务,它将比幼稚的阻止过程更快。如果您只想编写一些日志内容,请使用带有关联锁的TArray<string>

本文链接:https://www.f2er.com/2964425.html

大家都在问