Einzelnen Beitrag anzeigen

Schokohase
(Gast)

n/a Beiträge
 
#9

AW: Mutex zwischen 2 Prozessen

  Alt 2. Nov 2018, 13:53
Hier etwas funktionierendes zum Spielen
Delphi-Quellcode:
unit Unit1;

interface

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

type
  TForm1 = class( TForm )
    Button1: TButton;
    Button2: TButton;
    procedure Button1_Click( Sender: TObject );
    procedure Button2_Click( Sender: TObject );
  private
    FMutex: TMutex;
  public
    procedure AfterConstruction; override;
    procedure BeforeDestruction; override;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

const
  Mutex_Name = {$IFDEF GLOBAL}'global\'+{$ENDIF}'MyMutex';

procedure TForm1.AfterConstruction;
begin
  inherited;
  FMutex := TMutex.Create( nil, false, Mutex_Name );
end;

procedure TForm1.BeforeDestruction;
begin
  FMutex.Free;
  inherited;
end;

procedure TForm1.Button1_Click( Sender: TObject );
begin
  if FMutex.WaitFor( 0 ) = TWaitResult.wrSignaled
  then
    begin
      // We have the mutex
      Button1.Enabled := false;
      Button2.Enabled := True;
    end;
end;

procedure TForm1.Button2_Click( Sender: TObject );
begin
  // We have the mutex, so we release it
  FMutex.Release;
  Button1.Enabled := True;
  Button2.Enabled := false;
end;

end.
  Mit Zitat antworten Zitat