Multithreaded Application Tutorial/ja

This is an old revision of Multithreaded Application Tutorial/ja, edited by Vincent at . The current revision is 21834.

Text replace - "Delphi>" to "syntaxhighlight>"

日本語版メニュー
メインページ - Lazarus Documentation日本語版 - 翻訳ノート - 日本語障害情報

概�

��ページ�� Free Pascal � Lazarus を使��マル�スレッドアプリケーションを書��りデ�ッグ��り�る方法����述���。

も��読者�マル�スレッディング����触れる��ら�是�マル�スレッディング�本当�必�����を「マル�スレッディング�必�����節��確������。���れ�頭痛�種を激減�る�����る��ょ�。

マル�スレッドアプリケーション��2���れ以上�スレッドを作���時実行��作業を行�も���。����一���メインスレッド�呼�れるも���。メインスレッド�アプリケーション�起動�る際�オペレーティングシステム�よ��生��れ��。メインスレッド�ユーザーインターフェイス�コン�ー�ントを更新�る唯一�スレッド��。メインスレッド���ら���一���る必���り�������アプリケーション�暴走���。

マル�スレッドプログラミング�基本的�考�方��ユーザ�メインスレッドを通��作業�る�ら�も�一��スレッドを用���る種�処�を�ックグラウンド�行�るよ��アプリケーションを組む���点��。

スレッド�他�使�������アプリケーション�応答速度を改善�る���挙�られ��。例������アプリケーションを作り�ユーザー�ボタンを押���アプリケーション�処�を開始������(������処���)。処��間�スクリーン��り���応�無��り�ユーザー�アプリケーション���������ょ�。よ�������。も�������処�を2�目�スレッド�中�実行�るよ���れ��アプリケーション�応答性���れ��る��ん�処��行�������よ��振舞���。��よ��場����スレッドを開始�る��フォーム�処�を開始�るボタンを使用��能�������ユーザー��れ以上�仕事を�求�る��を無��������好都���。

���サー�アプリケーションを作る際���時�大��クライアント�応答���れ��ら��場��も使���。

マル�スレッディング�必����?

も�読者�マル�スレッディング��れ��触れ�����������処�を実行�るアプリケーション�応答性を改善������ら�マル�スレッディング��探��も������も�れ��ん。マル�スレッドアプリケーション�����複雑��り�デ�グ�常�困難��。���多��場�マル�スレッディング�必����も���。�一スレッドアプリケーション��分��。時間���るタスクを細��部分�分割�る�����る�ら�マル�スレッディング�代�り�Application.ProcessMessagesを使�����。��メソッド� LCL �待機中�メッセージを全�処���るも���。分割��タスク�一部分を実行��ら Application.ProcessMessages を呼��ユーザ�アプリケーションを終了���り���をクリック��り���を確����る��進行状�表示を��画��り���。��後タスク�次�部分を実行���� Application.ProcessMessages を呼���。

例: 大��ファイル�読�込��処�。examples/multithreading/singlethreadingexample1.lpi �照。

マル�スレッディング�必�����次�よ��場����� -

If You want to use multi-threading to increase speed by using multiple processors simultaneously, check if your current program now use all 100% resources of 1 core CPU (for example, you program can actively use input-output operations, e.g. writing to file; this takes a lot of time, but doesn't load CPU; in this case you program will not be faster with multiple threads). Also check if optimisation level is set to maximum (3). When I switched optimisation level from 1 to 3, my program became about 5 times faster.

TThreadクラス

��サンプル�「examples/multithreading/���り��。

マル�スレッドアプリケーション�TThreadクラスを使用�る�簡��作�����。��クラスを用�る�追加�スレッド(メインスレッド�並列�実行�る)を作る�������。

������通常�Create コンストラクタ��Execute メソッド�二��メソッドをオー�ーライド���れ��り��ん。

コンストラクタ������走ら�るスレッドを準備�る際�使���。����変数も���プロパティ��切��期値を��る必���り��。TThread �オリジナル�コンストラクタ� Suspended ���パラメータを必�����。���らも���り�よ���Suspended � False �場��スレッド�作�後直��実行�れ��。逆� Suspended � True �場��スレッド��止状態�作��れ��。��場��スレッドを走ら�る�� Resume メソッドを呼���。

FPC��ージョン�2.0.1����れ以��場��TThread.Create � StackSize ���暗黙�パラメータを������。����必��ら�自分�作るスレッド�デフォルトスタックサイズを変更�る����能��。 例��スレッド内�深��帰呼�出�を行�際�����る��ょ�。����スタックサイズを指定���れ��OS�よる�定�スタックサイズ�使用�れ��。

スレッド�実行���コード��Execute メソッドをオーヴァーライド�����中�書���。

TThread クラス�一�����プロパティを������。�れ�:

Terminated : boolean;

��。

Terminated �デフォルト値� False ��。通常�場��スレッド�ループを��������Terminated � True ����ら���ループ�ら脱出���れ��り��ん。�����ループ�サイクル毎��Terminated� True ���������ェック�る必���り��。も� True �������ら�速や��必��クリーンアップを行��Execute メソッドを終了����れ��り��ん。

���ら�Terminated メソッドを呼�出��もデフォルト状態��何も起�����を����り覚���������。Execute メソッド自体�自分自身を終了�るよ��明示的�実装���れ��り��ん。

先�説明��よ���スレッド��視コン�ー�ントを�作������り��ん。���をユーザー�表示�る����メインスレッド�行���。�れを行���� TThread ��Synchronize���メソッド��り��。��メソッド�引数����引数をも���一��メソッドを�り��。����MyMethod���メソッドをスレッド�ら実行�る���Synchronixe(@MyMethod)���呼�出���。��時スレッド�実行�一時的��止��メインスレッド�ら当該メソッド�実行�れ���後スレッド実行��開�れ��。��よ��仕組�������MyMethod�コンテクスト(文脈)を����実行�れ��。��り�mousedownイヴェントやpaintイヴェント実行中�割り込ん�実行�れる�������れら�イヴェント�処��終����ら実行�れ��。MyMethod�実行�れ�後�休眠状態������スレッド��開��次�メッセージ�処��れ��。

TThread ���も�一�����プロパティ��FreeOnTerminate ��り��。��プロパティを True �������スレッドオブジェクト�スレッド�実行(Executeメソッド)��止��後�自動的�解放�れ��。�も����アプリケーション�手動�オブジェクトを解放�る必���り��。

例:

  Type
    TMyThread = class(TThread)
    private
      fStatusText : string;
      procedure ShowStatus;
    protected
      procedure Execute; override;
    public
      Constructor Create(CreateSuspended : boolean);
    end;

  constructor TMyThread.Create(CreateSuspended : boolean);
  begin
    FreeOnTerminate := True;
    inherited Create(CreateSuspended);
  end;

  procedure TMyThread.ShowStatus;
  // ��メソッド�メインスレッド�実行�れる�� GUI �素�アクセス�る�������
  begin
    Form1.Caption := fStatusText;
  end;
 
  procedure TMyThread.Execute;
  var
    newStatus : string;
  begin
    fStatusText := 'TMyThread Starting...';
    Synchronize(@Showstatus);
    fStatusText := 'TMyThread Running...';
    while (not Terminated) and ([ä»–ã�®ãƒ«ãƒ¼ãƒ—終了æ�¡ä»]) do
      begin
        ...
        [here goes the code of the main thread loop]
        ...
        if NewStatus <> fStatusText then
          begin
            fStatusText := newStatus;
            Synchronize(@Showstatus);
          end;
      end;
  end;

アプリケーション���,

  var
    MyThread : TMyThread;
  begin
    MyThread := TMyThread.Create(True); // This way it doesn't start automatically
    ...
    [Here the code initialises anything required before the threads starts executing]
    ...
    MyThread.Resume;
  end;

も��柔軟�制御を望む�ら�スレッド�対�イヴェントを発行�る����� - ���る��sychronize�れ�メソッド�特定�フォームやクラス�縛られ���り�� - ��イヴェント�対�るリスナーを設定�る�������。次�例��TMyThread.ShowStatus�メインスレッド�実行�れる���全��GUI�素�触る�������:

  Type
    TShowStatusEvent = procedure(Status: String) of Object;

    TMyThread = class(TThread)
    private
      fStatusText : string;
      FOnShowStatus: TShowStatusEvent;
      procedure ShowStatus;
    protected
      procedure Execute; override;
    public
      Constructor Create(CreateSuspended : boolean);
      property OnShowStatus: TShowStatusEvent read FOnShowStatus write FOnShowStatus;
    end;

  constructor TMyThread.Create(CreateSuspended : boolean);
  begin
    FreeOnTerminate := True;
    inherited Create(CreateSuspended);
  end;

  procedure TMyThread.ShowStatus;
  // this method is executed by the mainthread and can therefore access all GUI elements.
  begin
    if Assigned(FOnShowStatus) then
    begin
      FOnShowStatus(fStatusText);
    end;
  end;

  procedure TMyThread.Execute;
  var
    newStatus : string;
  begin
    fStatusText := 'TMyThread Starting...';
    Synchronize(@Showstatus);
    fStatusText := 'TMyThread Running...';
    while (not Terminated) and ([any condition required]) do
      begin
        ...
        [here goes the code of the main thread loop]
        ...
        if NewStatus <> fStatusText then
          begin
            fStatusText := newStatus;
            Synchronize(@Showstatus);
          end;
      end;
  end;

アプリケーション���,

  Type
    TForm1 = class(TForm)
      Button1: TButton;
      Label1: TLabel;
      procedure FormCreate(Sender: TObject);
      procedure FormDestroy(Sender: TObject);
    private
      { private declarations }
      MyThread: TMyThread; 
      procedure ShowStatus(Status: string);
    public
      { public declarations }
    end;

  procedure TForm1.FormCreate(Sender: TObject);
  begin
    inherited;
    MyThread := TMyThread.Create(true);
    MyThread.OnShowStatus := @ShowStatus;
  end;

  procedure TForm1.FormDestroy(Sender: TObject);
  begin
    MyThread.Terminate;
    MyThread.Free;
    inherited;
  end;

  procedure TForm1.Button1Click(Sender: TObject);
  begin
   MyThread.Resume;
  end;

  procedure TForm1.ShowStatus(Status: string);
  begin
    Label1.Caption := Status;
  end;

(日本語訳注: FreeOnTerminate = True �使用��場��厄介���メイン��らスレッドを制御�る���常�困難��る����。例��上�コード例��FormDestroy や Button1Click �呼�れる�� MyThread.Execute �終了������ MyThread �自動解放�れ�場��正常�動作�る��疑��残り��。FreeOnTerminate = False ����使用���スレッドをメインスレッド�確実�制御�るやり方����より実用的��グも�������勧���。スレッド�止���もメモリ�解放�れ��点�デメリット����デメリット����工夫�より���気��ら��メモリ消費��済む�������ょ��。

FreeOnTerminate = False ���場��例:

  Type
    TMyThread = class(TThread)
    private
      fStatusText : string;
      procedure ShowStatus;
    protected
      procedure Execute; override;
    public
      Constructor Create(CreateSuspended : boolean);
    end;

  constructor TMyThread.Create(CreateSuspended : boolean);
  begin
    FreeOnTerminate := False;
    inherited Create(CreateSuspended);
  end;

  procedure TMyThread.ShowStatus;
  // ��メソッド�メインスレッド�実行�れる�� GUI �素�アクセス�る�������。
  // ���共有変数��書�込�も��メソッド�やれ����動作���。
  begin
    Form1.Caption := fStatusText;
  end;
 
  procedure TMyThread.Execute;
  var
    newStatus : string;
  begin
    try
      fStatusText := 'TMyThread Starting...';
      Synchronize(@Showstatus);
      fStatusText := 'TMyThread Running...';
      while (not Terminated) and ([ä»–ã�®ãƒ«ãƒ¼ãƒ—終了æ�¡ä»]) do
        begin
          ...
          [here goes the code of the main thread loop]
          ...
          if NewStatus <> fStatusText then
            begin
              fStatusText := newStatus;
              Synchronize(@Showstatus);
            end;
        end;
    finally
      fStatusText := ''; // メモリを節約�る��空�
    end;
  end;
  
  ...
  //--- アプリケーション� --------------------------------------
  ...

 TForm1 = class(TForm)
   ...
   MyThread : TMyThread;
   ...
 end;

 procedure TForm1.FormCreate(Sender: TObject);
 begin
   MyThread := nil;
 end;
 
 procedure TForm1.FormDestroy(Sender: TObject);
 begin
   if Assigned(MyThread) then MyThread.Free;
 end;
 
 procedure TForm1.Button1Click(Sender: TObject);
 begin
   if Assigned(MyThread) then
   begin
     MyThread.Terminate; 
     MyThread.WaitFor; 
     MyThread.Free; 
     MyThread := nil;
   end;
 
   MyThread := TMyThread.Create(True); // �作�
   ...
   [Here the code initialises anything required before the threads starts executing]
   ...
   MyThread.Resume; // �スタート
 end;

日本語訳注終�り)

特別�注������

Windows ���るスタック�ェック

Windows�-Ctスイッ�(スタック�ェック)を���スレッド��頭�痛��題��り��。�由�定����り��ん��デフォルト�スタックサイズを使�場��スタック�ェック� TTread.Create をトリガー���������り��。�在��用上�回�策���� -Ctスイッ�を使�������。�れ�メインスレッド�例外を��������全����新��生��れ�スレッド�起�り��。����スレッド�絶対開始����よ��見���。

スレッド生�時�発生�る��他�例外や����題を�ェック�る良�コードを示���。

    MyThread:=TThread.Create(False);
    if Assigned(MyThread.FatalException) then
      raise MyThread.FatalException;

��コード�スレッド生�時�発生�る�ん�例外�も�メイン�スレッド�raise�るよ�����。

マル�スレッドアプリケーション�必��ユニット

Windows��特�気を��る����������LinuxやMaxOSX,FreeBSD�����ら�プロジェクト�ユニット(��り�プログラムユニット�.lpr)��cthreadsユニットをuses�る必���り��。

Lazarusアプリケーション�コード��次�よ���る��ょ�。

program MyMultiThreadedProgram;
{$mode objfpc}{$H+}
uses
{$ifdef unix}
  cthreads,
  cmem, // the c memory manager is on some systems much faster for multi-threading
{$endif}
  Interfaces, // this includes the LCL widgetset
  Forms
  { you can add units here },

�れを怠る��起動時�次�エラー�出��:

 This binary has no thread support compiled in.
 Recompile the application with a thread-driver in the program uses clause before other units using thread.

Multithreading in packages

Packages which uses multi-threading should add the -dUseCThreads flag to the custom usage options. Open the package editor of the package, then Options > Usage > Custom and add -dUseCThreads. This will define this flag to all projects and packages using this package, including the IDE. The IDE and all new applications created by the IDE have already the following code in their .lpr file:

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  cmem, // the c memory manager is on some systems much faster for multi-threading
  {$ENDIF}{$ENDIF}
</DELPHI>

===Heaptrc===

You can not use the -gh switch with the ''cmem'' unit. The -gh switch uses the heaptrc unit, which extends the heap manager. Therefore the '''heaptrc''' unit must be used '''after''' the '''cmem''' unit.

<syntaxhighlight>uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  cmem, // the c memory manager is on some systems much faster for multi-threading
  {$ENDIF}{$ENDIF}
  heaptrc,</DELPHI>

== SMP(対称型マル�プロセッサCPU)�サ�ート ==
良�ニュース��。��用法�マル�スレッド�アプリケーション���正��動作�れ���れ�SMP�並列動作�有効��り��。

== Lazarus��マル�スレッド�デ�ッグ ==
Lazarus��マル�スレッド�デ�ッグ����完全�機能���ん。

=== デ�グ出力 ===
シングルスレッドアプリケーションã�§ã�¯ã€�å�˜ã�«ã‚³ãƒ³ã‚½ãƒ¼ãƒ«/ターミナル/ã��ã�®ä»–ã�«ä¸€è¡Œä¸€è¡Œå‡ºåŠ›ã�™ã‚Œã�°ã€�ã��ã�®é †åº�ã�«æ›¸ã��è¾¼ã�¾ã‚Œã�¾ã�™ã€‚マルãƒ�スレッドアプリケーションã�§ã�¯ã��ã�†ã�¯å•�屋ã�Œå�¸ã�—ã�¾ã�›ã‚“。二ã�¤ã�®ã‚¹ãƒ¬ãƒƒãƒ‰A,Bã�Œã�‚りã€�ã�¾ã�šAã�Œã€�次ã�„ã�§Bã�Œè¡Œã‚’出力ã�—ã�Ÿã�¨ã�—ã�¾ã�™ã€‚ã�—ã�‹ã�—ã€�å¿…ã�šã�—ã‚‚ã��ã�®é †åº�ã�§è¡Œã�Œä¸¦ã�ã‚�ã�‘ã�§ã�¯ã�‚りã�¾ã�›ã‚“。ã�•らã�«ã�¯ã€�行ã�®é€”中ã�§åˆ¥ã�®ã‚¹ãƒ¬ãƒƒãƒ‰ã�®å‡ºåŠ›ã�Œå‰²ã‚Šè¾¼ã‚“ã�§ã��ã‚‹ã�“ã�¨ã� ã�£ã�¦ã�‚り得ã�¾ã�™ã€‚

LCLProcユニットã�«ã€�スレッド毎ã�«ãƒ­ã‚°ã‚’ä¿�å­˜ã�™ã‚‹ã�Ÿã‚�ã�®æ‰‹çšã��ã�Œã�‚りã�¾ã�™:
  procedure DbgOutThreadLog(const Msg: string); overload;
  procedure DebuglnThreadLog(const Msg: string); overload;
  procedure DebuglnThreadLog(Args: array of const); overload;
  procedure DebuglnThreadLog; overload;

例:
''writeln('Some text ',123);'' �代�り���れを使��� 
  DebuglnThreadLog(['Some text ',123]);

���る�� 'Some text 123' ���行� '''Log<PID>.txt''' �追加�れ��。��� <PID> ���スレッド�プロセスID��。

実行�る�毎��ログファイルを削除�る�よ���ょ�:
  rm -f Log* && ./project1

=== Linux ===
も�マル�スレッドアプリケーションをLinux�デ�ッグ�よ���る��Xサー�ー��ング�る����大���題�直��る��ょ�。

�れ���や��解決����分������ん��回�策�����X�インスタンスを次�よ��新��作り��。

  X :1 &

�れ�Open���他�デスクトップ�スイッ������(the one you are working with pressing CTRL+ALT+F7), 元�グラフィカルデスクトップ�CTRL+ALT+F8�戻る�������。
(も���組��������������らSlackware��CTRL+ALT+F2�)

も���れ����ら�X�開始�るデスクトップセッションを次�よ����作り��。

  gnome-session --display=:1 &

���Lazarus�プロジェクト� run parameters dialog�"Use display"を�ェック���:1を入力���。

�れ�アプリケーション�2番目�Xサー�ー�動作�るよ���り�最��Xサー�ー�デ�ッグ��能��り���。

��方法��FPC2.0�Lazarus 0.9.10��OS�Windows�Linux�テスト����。

----

新�� X セッションを開始�る代�り�� [http://en.wikipedia.org/wiki/Xnest Xnest] を用�る��も����。Xnest � X セッションをウィンドウ�開�も���。�れを用�る��スレッドをデ�グ�る間も X サー��ロック���ん。���複数�ターミナルを行��り��り���らデ�グ�るよりも楽��。

Xnestを起動�る���次�よ��コマンドをタイプ���:

  Xnest :1 -ac

一ã�¤ã�® X セッションã�Œ :1 ã�§é–‹ã��ã€�アクセスåˆå¾¡ã�Œãƒ‡ã‚£ã‚»ãƒ¼ãƒ–ルã�•れã�¾ã�™ã€‚

== ウィジェットセット ==

Win32�gtk�Carbon インタフェース�マル�スレッディングを完全�サ�ート�����。�� TThread�クリティカル・セクション�Synchronize �動作���。

===Using SendMessage/PostMessage to communicate between threads===

Only one thread in an application should call LCL APIs, usually the main thread. Other threads can make use of the LCL through a number of indirect methods, one good option being the usage of SendMessage or PostMessage. LCLIntf.SendMessage and LCLIntf.PostMessage will post a message directed to a window in the message pool of the application.

See also the documentation for these routines: 
*http://lazarus-ccr.sourceforge.net/docs/lcl/lclintf/sendmessage.html
*http://lazarus-ccr.sourceforge.net/docs/lcl/lclintf/postmessage.html

The difference between SendMessage and PostMessage is the way that they return control to the calling thread. With SendMessage control is not returned until the window that the message was sent to has completed processing the sent message, however with PostMessage control is returned immediately.

Here is an example of how a secondary thread could send text to be displayed in an LCL control to the main thread:

<syntaxhighlight>
const
  WM_GOT_ERROR           = LM_USER + 2004;
  WM_VERBOSE             = LM_USER + 2005;

procedure VerboseLog(Msg: string);
var
  PError: PChar;
begin
  if MessageHandler = 0 then Exit;
  PError := StrAlloc(Length(Msg)+1);
  StrCopy(PError, PChar(Msg));
  PostMessage(formConsole.Handle, WM_VERBOSE, Integer(PError), 0);
end;

And an example of how to handle this message from a window:

const
  WM_GOT_ERROR           = LM_USER + 2004;
  WM_VERBOSE             = LM_USER + 2005;

type
  { TformConsole }

  TformConsole = class(TForm)
    DebugList: TListView;
    // ...
  private
    procedure HandleDebug(var Msg: TLMessage); message WM_VERBOSE;
  end;

var
  formConsole: TformConsole;

implementation

....

{ TformConsole }

procedure TformConsole.HandleDebug(var Msg: TLMessage);
var
  Item: TListItem;
  MsgStr: PChar;
  MsgPasStr: string;
begin
  MsgStr := PChar(Msg.wparam);
  MsgPasStr := StrPas(MsgStr);
  Item := DebugList.Items.Add;
  Item.Caption := TimeToStr(SysUtils.Now);
  Item.SubItems.Add(MsgPasStr);
  Item.MakeVisible(False);
  //f/TrayControl.SetError(MsgPasStr);
end;

end.

クリティカル・セクション

クリティカル・セクション�オブジェクト�一����る部分�コード��る時点��一��スレッド���実行�れる��(排他的�実行�れる��)を�証�るも���。クリティカル・セクション�使用��作���期化��使用後�解放�る必���り��。

通常�使�方��:

セクションを宣言���。(��セクションを実行�る�能性��る全��スレッド�ら見�るよ��分大域�宣言���れ��り��ん):

 MyCriticalSection: TRTLCriticalSection;

セクションを作����:

 InitializeCriticalSection(MyCriticalSection);

�����スレッドを走ら���。���排他的����を�る��次�よ�����:

EnterCriticalSection(MyCriticalSection);
try
  // access some variables, write files, send some network packets, etc
finally
  LeaveCriticalSection(MyCriticalSection);
end;

全��スレッド��止��後�セクションを解放���:

 DeleteCriticalSection(MyCriticalSection);

別�方法����TCriticalSection オブジェクトも使���。オプジェクトを作��る�セクション�作���期化を�Enter メソッドを実行�る� EnterCriticalSection ��様�動作を�Leave メソッドを実行�る� LeaveCriticalSection ��様�動作を�オブジェクトを破棄�る�セクション�削除を行���。

For example: 5 threads incrementing a counter. See lazarus/examples/multithreading/criticalsectionexample1.lpi

注�: 上記�4��手続�� RTL(FPC�ランタイム)� LCL �一組��存在���。RTL �� SyncObjs ユニット��り����LCL �� LCLIntf ユニット� LCLType �定義�れ����。��ら�組も�様�用�る�������。アプリケーション�中�混用�る��も������RTL �関数�手続��� RTL �クリティカルセクションを�LCL �関数�手続��� LCL �クリティカルセクションを使���れ��り��ん。

変数�共用

複数�スレッド�一��変数を共用�る場��読�出����ら何も�題��り��ん。��読�������。����一����複数�スレッド���値を変更�よ���る�ら�複数�スレッド���変数��時�アクセス���よ��注����れ��り��ん。

例: 五��スレッド�一��カウンタをインクリメント���。

lazarus/examples/multithreading/criticalsectionexample1.lpi �照。

別�スレッド�処�を待�方法

スレッドA�別�スレッドB��果を利用�る�ら�A�B�処��終了�る��待�必���り��。

��: メインスレッド�決��他�スレッド�処�を待�������ん。��代�り�上記� Synchronize を用���。

�照���例: lazarus/examples/multithreading/waitforexample1.lpi

{ TThreadA }

procedure TThreadA.Execute;
begin
  Form1.ThreadB:=TThreadB.Create(false);
  // create event
  WaitForB:=RTLEventCreate;
  while not Application.Terminated do begin
    // wait infinitely (until B wakes A)
    RtlEventWaitFor(WaitForB);
    writeln('A: ThreadB.Counter='+IntToStr(Form1.ThreadB.Counter));
  end;
end;

{ TThreadB }

procedure TThreadB.Execute;
var
  i: Integer;
begin
  Counter:=0;
  while not Application.Terminated do begin
    // B: Working ...
    Sleep(1500);
    inc(Counter);
    // wake A
    RtlEventSetEvent(Form1.ThreadA.WaitForB);
  end;
end;

Fork

When forking in a multithreaded application, be aware that any threads created and running BEFORE the fork (or fpFork) call, will NOT be running in the child process. As stated on the fork() man page, any threads that were running before the fork call, their state will be undefined.

So be aware of any threads initializing before the call (including on the initialization section). They will NOT work.

Parallel procedures/loops

A special case of multi threading is running a single procedure in parallel. See Parallel procedures.

Distributed computing

The next higher steps after multi threading is running the threads on multiple machines.

External threads

To make Free Pascal's threading system to work properly, each newly created FPC thread needs to be initialized (more exactly, the exception, I/O system and threadvar system per thread needs to be initialized so threadvars and heap are working). That is fully automatically done for you if you use BeginThread (or indirectly by using the TThread class). However, if you use threads that were created without BeginThread (i.e. external threads), additional work (currently) might be required. External threads also include those that were created in external C libraries (.DLL/.so).

Things to consider when using external threads (might not be needed in all or future compiler versions):

If the calling convention doesn't fit (e.g. if your original thread function needs cdecl calling convention but BeginThread needs pascal convention, create a record, store the original required thread function in it, and call that function in your pascal thread function:

type 
 TCdeclThreadFunc = function (user_data:Pointer):Pointer;cdecl; 

 PCdeclThreadFuncData = ^TCdeclThreadFunc; 
 TCdeclThreadFuncData = record
   Func: TCdeclThreadFunc;  //cdecl function
   Data: Pointer;           //original data
 end;     

// The Pascal thread calls the cdecl function
function C2P_Translator(FuncData: pointer) : ptrint;
var
  ThreadData: TCdeclThreadFuncData;
begin 
  ThreadData := PCdeclThreadFuncData(FuncData)^;
  Result := ptrint(ThreadData.Func(ThreadData.Data));
end; 

procedure CreatePascalThread;
var
  ThreadData: PCdeclThreadFunc; 
begin 
  New(ThreadData);
  // this is the desired cdecl thread function
  ThreadData^.Func := func; 
  ThreadData^.Data := user_data;    
  // this creates the Pascal thread
  BeginThread(@C2P_Translator, ThreadData );
end;
type
   tc = class(tthread)
     procedure execute;override;
   end;

   procedure tc.execute;
   begin
   end;

{ main program } 
begin
  { initialise threading system }
   with tc.create(false) do
   begin
     waitfor;
     free;
   end;
   { ... your code follows } 
end.

(After the threading system is initialized, the runtime may set the system variable "IsMultiThread" to true which is used by FPC routines to perform locks here and there. You should not set this variable manually.)

function ExternalThread(param: Pointer): LongInt; stdcall;
var
  tm: TThreadManager;
begin
  GetThreadManager(tm);
  tm.AllocateThreadVars;
  InitThread(1000000); // adjust inital stack size here
  
  { do something threaded here ... }
    
  Result:=0;
end;

Identifying external threads

Sometimes you even don't know if you have to deal with external threads (e.g. if some C library makes a callback). This can help to analyse this:

1. Ask the OS for the ID of the current thread at your application's start

Win32: GetCurrentThreadID();
Darwin: GetThreadID();  
Linux: TThreadID(pthread_self);

2. Ask again for the ID of the current thread inside the thread function and compare this by the result of step 1.

Give up some time slice

ThreadSwitch()

Note: Do not use the Windows trick Sleep(0) as this won't work on all platforms.

See also