Sign in Join
Wiki copytemporary

Example of multi-threaded application: array of threads/ja: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Example of multi-threaded application: array of threads/ja

OldNewLine
1+ここで、私は多数のスレッドを生成して、それらが作業を終えるのを待つ例を示そうと思います(同期は必要としていません)。これを書く気になったのは、[[Multithreaded Application Tutorial/ja|Multithreaded Application Tutorial/jaを]]読んでも、その種のプログラムを書く方法がはっきり判らなかったからです。私が書いているのはOS X用のアプリケーションですが、ここに出てきたコードはどんなシステムでも動作するでしょう。
2+
3+次のようなループを考えてみましょう:
4+
5+``` pascal
6+...
7+for i := 1 to n do power(i, 0.5)
8+...
9+```
10+
11+このループは、冪乗を一つづつ n 回計算しています。スレッドを使って同じことを並列に処理させてみましょう。
12+
13+## マルチスレッドは必要なの?
14+
15+現代のマルチコアコンピュータでは、マルチスレッドを利用すればパフォーマンスが劇的に改善する場合があります。しかしながら、現代のコンピュータは極めて高速であり、スレッド化したコードは逐次処理に比べ、しばしばデバグと保守が困難です。処理時間の短縮とマルチスレッドプログラミングの複雑さとを天秤に掛け、またアルゴリズムが並列処理に適しているかよく考えてみる必要があります。最後に、並列処理の中にも、CPUスレッドの利用が適している場合(この例)とGPUの利用が適している場合があることを知っていてください(後者の場合、OpenCLのようなツールが最適です)。
16+
17+## メモリのマネジメント
18+
19+複数のスレッドが同時に動作するため、それらがメモリを獲り合わないようにする必要があります。このメモリの競合問題は複数のスレッドがメモリの同じ場所に書き込もうとする場合に発生します。ある種のアルゴリズムは各計算処理がそれまでの結果に依存するため、そもそもマルチスレッディングに適していません。一方、各計算処理が独立かつ並列に行える問題に対しては、マルチスレッディングは極めて有効です。今回の例では、各処理が完全に独立しており、故にマルチスレッドで容易に攻略できる課題を解こうと思います。更に進んだアルゴリズムでは、メモリのロック機能を用いて、競合を避ける必要が出てくるでしょう。
20+
21+今回の例では、各スレッドがそれぞれ異なるメモリの場所に書き込みます。もっと具体的に言えば、1..n の配列を作り、その範囲の i に対して power(i, 0.5) の値を計算します。各スレッドは計算処理の独立した部分を受け持ちます。n = 1000 だとします。一つのスレッドだけを使うなら、1..1000 の全体を扱うことになります。スレッドが二つなら、一つが 1..500 を、もう一つが 501..1000 に取り組むようにできます。このようにして、各スレッドが異なったメモリ部分を埋めていけるわけです。
22+
23+## 1. 利用できるコアの数を検出する
24+
25+コアを一つしか持たないコンピュータではスレッド化の効用はありませんが、物理コアが四つのコンピュータは、ハイパースレッディング(二つのタスクを同時実行可能にする)によって最大八個のタスクを同時に処理することができます。次の cpucount ユニットは利用可能なコア数を返します。あるコンピュータに於いて走らせるべきスレッドの数を決めるのにこれが使えます。四つ以上のコアを持つコンピュータでは、コア数を n とすれば、n-1 個のスレッドを走らせたくなるでしょう。残りの一つは GUI など他のタスク用にとっておきます。これだけコアがあれば、n と n-1 では処理速度に大差がありませんから。
26+
27+``` pascal
28+unit cpucount;
29+{$mode objfpc}
30+
31+interface
32+//コンピュータのコア数を返す。ハイパースレッドを使った2コアのコンピュータでは4が返るだろう。
33+function GetLogicalCpuCount: Integer;
34+
35+implementation
36+
37+{$IF defined(windows)}
38+uses windows;
39+{$endif}
40+
41+{$IF defined(darwin)}
42+uses ctypes, sysctl;
43+{$endif}
44+
45+{$IFDEF Linux}
46+uses ctypes;
47+
48+const _SC_NPROCESSORS_ONLN = 83;
49+function sysconf(i: cint): clong; cdecl; external name 'sysconf';
50+{$ENDIF}
51+
52+
53+function GetLogicalCpuCount: integer;
54+// 当該システム上で適切なスレッドの数のデフォルト値を返す
55+{$IF defined(windows)}
56+// ハイパースレッドを含んで、システム上で利用可能なプロセッサの数を返す。
57+var
58+ i: Integer;
59+ ProcessAffinityMask, SystemAffinityMask: DWORD_PTR;
60+ Mask: DWORD;
61+ SystemInfo: SYSTEM_INFO;
62+begin
63+ if GetProcessAffinityMask(GetCurrentProcess, ProcessAffinityMask, SystemAffinityMask)
64+ then begin
65+ Result := 0;
66+ for i := 0 to 31 do begin
67+ Mask := DWord(1) shl i;
68+ if (ProcessAffinityMask and Mask)<>0 then
69+ inc(Result);
70+ end;
71+ end else begin
72+ //affinity mask が得られなかったので、単にプロセッサの数を報告する
73+ GetSystemInfo(SystemInfo);
74+ Result := SystemInfo.dwNumberOfProcessors;
75+ end;
76+end;
77+{$ELSEIF defined(UNTESTEDsolaris)}
78+ begin
79+ t = sysconf(_SC_NPROC_ONLN);
80+ end;
81+{$ELSEIF defined(freebsd) or defined(darwin)}
82+var
83+ mib: array[0..1] of cint;
84+ len: cint;
85+ t: cint;
86+begin
87+ mib[0] := CTL_HW;
88+ mib[1] := HW_NCPU;
89+ len := sizeof(t);
90+ fpsysctl(pchar(@mib), 2, @t, @len, Nil, 0);
91+ Result:=t;
92+end;
93+{$ELSEIF defined(linux)}
94+ begin
95+ Result:=sysconf(_SC_NPROCESSORS_ONLN);
96+ end;
97+
98+{$ELSE}
99+ begin
100+ Result:=1;
101+ end;
102+{$ENDIF}
103+end.
104+```
105+
106+ユニット **MTPCPU** 内の **GetSystemThreadCount** 関数は、同様のロジックで利用可能なコアの数を報告します。このユニットは lazarus/components/multithreadprocs/mtpcpu.pas にあります。
107+
108+``` pascal
109+Program CPUCountTest;
110+uses MTPCPU;
111+begin
112+ writeln(GetSystemThreadCount)
113+end.
114+```
115+
116+例えば Intel Core2Duo を一個だけ持っている旧式 MacBook では結果は 2 となります。
117+
118+## 2. カスタムスレッドクラスの生成
119+
120+複数のスレッドの動作を定義するために専用のユニットを一つ作成します。FreeOnTerminate を false にしていることに注意してください。そのため、各スレッドが動作終了した後でそれらを dispose する必要があります。これによって、複数のスレッドをうまく扱えます(FreeOnTerminate を true にして、高速なジョブを複数立ち上げると、あるスレッドの動作完了をプログラム側が検査する前にそのスレッドが解放されてしまう可能性があり、存在しないスレッドを検査しようとすると例外を発生するかもしれません)。FreeOnTerminate を false にすれば、全てのスレッドが正常に終了したことを確認できます。
121+
122+``` pascal
123+unit mythreads;
124+{$mode objfpc}{$H+}
125+interface
126+uses Classes;
127+type
128+ TData = array of double;
129+ PData = ^TData;
130+ Type
131+ TMyThread = class(TThread)
132+ private
133+ protected
134+ tPtr: PData;
135+ tstart,tfinish: integer;
136+ procedure Execute; override;
137+ public
138+ property Terminated;
139+ Constructor Create(lstart, lfinish: integer; lPtr: PData);
140+ end;
141+
142+implementation
143+uses SysUtils, Math;
144+
145+ constructor TMyThread.Create(lstart, lfinish: integer; lPtr: PData);
146+ begin
147+ FreeOnTerminate := False;
148+ tstart := lstart;
149+ tfinish := lfinish;
150+ tPtr := lPtr;
151+ inherited Create(false)
152+ end;
153+
154+ procedure TMyThread.Execute;
155+ var i: integer;
156+ begin
157+ for i := tstart to tfinish do tPtr^[i] := power(i, 0.5)
158+ end;
159+
160+end.
161+```
162+
163+## 3. メインプログラムを書く
164+
165+メインユニットに cthread を入れる必要があります。スレッドのユニットにではありませんよ。
166+
167+全スレッドの終了を調べるために二つの方法があることにご注意ください。一つは組み込みの WaitFor 関数です。これは大変うまく動きますが、私のOS X機では、100 ms毎にしか更新されないようです。これはリアルワールドプログラミングでは完璧であり(計算機的には低速な課題にのみスレッディングを用います)、スレッドオーヴァヘッドが減りますが、短時間で済んでしまうようなベンチマークの例としては、スレッド化の効能を隠してしまうかもしれません(いくつスレッドを動かしても、最低でも100 msかかるので)。そこで、この例ではスレッドの終了状態を 2 msおきに調べています。これで更に正確な実行時間のベンチマークが得られます。
168+
169+スレッドの利用が終わった時にそれを解放するのを忘れないでください。FreeOnTerminate を false にしてあるので、明示的にこれを行う必要があります。
170+
171+Tips: 私の Lazarus IDE では、マルチスレッドアプリケーションのデバグに pthreads が必要です。cmem を使うとプログラムの実行速度が上がるとも聞きますが、各自の環境でチェックされるよう強く勧めます(cmem を使うと私のプログラムはハングします)。
172+
173+``` pascal
174+uses // cmem,pthreads,
175+ cthreads, Classes, SysUtils, CustApp, MyThreads, Math, cpucount;
176+
177+procedure DoUnThreaded (nValues: integer);
178+var
179+ dataArray: TData;
180+ i: integer;
181+ StartMS: double;
182+begin
183+ if (nValues < 1) then exit;
184+ StartMS:=timestamptomsecs(datetimetotimestamp(now));
185+ setlength(dataArray, nValues+1);//0ベースなので +1する
186+ for i:=1 to nValues do
187+ dataArray[i] := power(i,0.5); ;
188+ Writeln('Serially processed '+inttostr(nValues)+' values in '+floattostr(timestamptomsecs(datetimetotimestamp(now))-StartMS)+'ms, with '+inttostr(nValues)+'^0.5 = '+floattostr(dataArray[nValues]));
189+end;
190+
191+procedure DoThreading (nThreadsIn, nValues: integer);
192+var
193+ threadArray: array of TMyThread;
194+ dataArray: TData;
195+ lData : PData;
196+ nThreads, i,lStart,lFinish: integer;
197+ StartMS: double;
198+begin
199+ if (nThreadsIn < 1) or (nValues < 1) then exit;
200+ nThreads := nThreadsIn;
201+ if nThreads > nValues then nThreads := nValues;
202+ StartMS:=timestamptomsecs(datetimetotimestamp(now));
203+ setlength(threadArray,nThreads+1);//0ベースなので +1する
204+ setlength(dataArray, nValues+1);//0ベースなので +1する
205+ lData := @dataArray;
206+ lStart := 1;
207+ for i:=1 to nThreads do begin
208+ if i < nThreads then
209+ lFinish:=i*(nValues div nThreads)
210+ else
211+ lFinish:= nValues;
212+ threadArray[i]:= TMyThread.Create(lStart, lFinish, lData);
213+ //Writeln('Thread '+inttostr(i)+' processing '+inttostr(lStart)+'..'+inttostr(lFinish));
214+ lStart := lFinish+1;
215+ end;
216+ for i:=1 to nThreads do if not ThreadArray[i].Terminated then Sleep(2);
217+ //for i:=1 to nThreads do threadArray[i].waitFor; //OS Xでは100 msスリープするようだ
218+ for i:=1 to nThreads do threadArray[i].Free;
219+ Writeln(inttostr(nThreads)+' Threads processed '+inttostr(nValues)+' values in '+floattostr(timestamptomsecs(datetimetotimestamp(now))-StartMS)+'ms, with '+inttostr(nValues)+'^0.5 = '+floattostr(dataArray[nValues]));
220+end;
221+
222+begin
223+ Writeln('コンピュータの報告によるとコア数は '+inttostr(GetLogicalCpuCount)+' : 最適と思われるスレッド数 ');
224+ DoUnthreaded(10);
225+ DoThreading(1,10);
226+ DoThreading(2,10);
227+ DoThreading(4,10);
228+ DoThreading(8,10);
229+ DoUnthreaded(100000000);
230+ DoThreading(1,100000000);
231+ DoThreading(2,100000000);
232+ DoThreading(4,100000000);
233+ DoThreading(8,100000000);
234+end.
235+```
236+
237+## 結果
238+
239+以下の結果が示す通り、スレッド作成の際に遅延が認められますが、タスクが大きくなると、マルチスレッドによる並列処理が順次処理を上回る性能を見せます。スレッド数がコア数(このコンピュータでは4)を超えると、スレッド数を増やす効能はほとんどなくなることにご注意ください。スレッド数と実行速度が単純に比例すると期待してはいけません: スレッド化にはいくらかのオーヴァヘッドがつきまといますし、最近のCPUは一つのタスクに集中して処理を行う場合、複数のコアを利用する場合よりも若干高速に動作します(「ターボブースト」)。
240+
241+- Computer reports 4 cores: probably optimal number of threads
242+- Serially processed 10 values in 0ms, with 10^0.5 = 3.16227766016838
243+- 1 Threads processed 10 values in 3ms, with 10^0.5 = 3.16227766016838
244+- 2 Threads processed 10 values in 5ms, with 10^0.5 = 3.16227766016838
245+- 4 Threads processed 10 values in 9ms, with 10^0.5 = 3.16227766016838
246+- 8 Threads processed 10 values in 19ms, with 10^0.5 = 3.16227766016838
247+- Serially processed 100000000 values in 10214ms, with 100000000^0.5 = 10000
248+- 1 Threads processed 100000000 values in 10320ms, with 100000000^0.5 = 10000
249+- 2 Threads processed 100000000 values in 5894ms, with 100000000^0.5 = 10000
250+- 4 Threads processed 100000000 values in 3801ms, with 100000000^0.5 = 10000
251+- 8 Threads processed 100000000 values in 3733ms, with 100000000^0.5 = 10000
252+
253+---
254+*From the Free Pascal wiki, page "Example of multi-threaded application: array of threads/ja", as it stood on 2020-02-14 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history