delphi 线程同步(线程安全)


本文整理自网络,侵删。

 
unit Unit1;

interface

uses
  uSyncThread, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  TWorkingThread.Create(False);
  TWorkingThread.Create(False);
  TWorkingThread.Create(False);
end;

end.





unit uSyncThread;

interface

uses
  System.SyncObjs, System.SysUtils, System.Classes;

type
  TWorkingThread = class(TThread)
  private
    { Private declarations }
  protected
    procedure Execute; override;
  public
    procedure Work();
  end;

implementation

uses
  Unit1;
{

线程安全

  1、多个线程共享一块数据,保证该数据执行的结果是正确的

解决方案

  1、线程同步(线程安全) 、VCL控件大部分是线程不安全的

  2、Delphi的具体实现方式

    a) Synchronize

    b) 临界区(TCriticalSection)

    c) 互斥体(TMutex)

    d) 信号量(TEvent)

    e) TMonitor

  3、使用场景

      1、当多个线程访问一个对象(数据)时,为了保证数据的正确性我们需要同步

      2、线程同步:可以保证数据的安全性,慢(效率低)

      3、线程异步:快(效率高)、无法保证数据的安全性

  4、扩展知识
      1、线程池 System.Threading.TThreadPool
}

var
  i: Integer;
  CriticalSection: TCriticalSection;
{ TWorkingThread }

procedure TWorkingThread.Execute;
begin
  FreeOnTerminate := True;
//  Self.Synchronize(Work);
  CriticalSection.Enter;
  Work();
  CriticalSection.Leave;
end;

procedure TWorkingThread.Work;
begin
  while True do begin
    Form1.Memo1.Lines.Add('线程编号:' + self.ThreadID.ToString + ',' + i.ToString);
    if i = 10 then begin
      Exit;
    end;
    inc(i);
   Self.Sleep(100);
  end;
end;

initialization
  CriticalSection := TCriticalSection.Create;

finalization
  CriticalSection.Free;

end.

相关阅读 >>

Delphi 防止程序重复执行(多种方法)

Delphi中简单的调用单元unit实例

Delphi 在richedit中插入gif图片的方法

Delphi ifileoperation替换shfileoperation

Delphi android / ios应用程序中使用tgeocoder类进行反向地理编码(从位置信息中获取地址)

几个webbrowser相关的函数

Delphi 关于汉字换行问题

Delphi base64单元encddecd的修改

Delphi 枚举所有电脑磁盘

Delphi firemonkey里触发home按键被按下的事件

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...