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动态创建一个ipedit控件

Delphi adoquery查询更改用户

Delphi gettempdirectory 获取临时文件夹路径

Delphi回调函数高级应用

Delphi closehandle的解释

Delphi jpeg压缩的两种方法

Delphi doc转txt

Delphi 利用createservice写与桌面交互的win32服务

Delphi hex 相关单元

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



打赏

取消

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

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

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

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

评论

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