perlthrtut > 5.10.1 との差分

perlthrtut 5.10.1 と 5.40.0 の差分

11
2=encoding euc-jp
2=encoding utf8
33
44=head1 NAME
55
66=begin original
77
88perlthrtut - Tutorial on threads in Perl
99
1010=end original
1111
1212perlthrtut - Perl におけるスレッドのチュートリアル
1313
1414=head1 DESCRIPTION
1515
1616=begin original
1717
1818This tutorial describes the use of Perl interpreter threads (sometimes
19referred to as I<ithreads>) that was first introduced in Perl 5.6.0. In this
19referred to as I<ithreads>). In this
2020model, each thread runs in its own Perl interpreter, and any data sharing
2121between threads must be explicit. The user-level interface for I<ithreads>
2222uses the L<threads> class.
2323
2424=end original
2525
26このチュートリアルは、Perl 5.6.0 において導入された新しい Perl インタプリタ
26このチュートリアルは、Perl インタプリタスレッド(B<iスレッド>(B<ithreads>)と
27スレッド(B<iスレッド>(B<ithreads>)と呼ばれる)の特徴を説明するものです。
27呼ばれる)の特徴を説明するものです。
2828このモデルにおいては、それぞれのスレッドはそれ自身の Perl インタプリタで
2929実行され、スレッド間で共有するデータも明示的でなければなりません。
3030I<ithreads> のユーザーレベルインターフェースは L<threads> クラスを使います。
3131
3232=begin original
3333
3434B<NOTE>: There was another older Perl threading flavor called the 5.005 model
35that used the L<Threads> class. This old model was known to have problems, is
35that used the L<threads> class. This old model was known to have problems, is
3636deprecated, and was removed for release 5.10. You are
3737strongly encouraged to migrate any existing 5.005 threads code to the new
3838model as soon as possible.
3939
4040=end original
4141
42B<注意>: Perl のバージョン 5.005 には、5.005 モデルと呼ばれる
42B<注意>: 5.005 モデルと呼ばれるL<threads> クラスを使う別の古いスレッド機能が
43L<Threads> クラスを使う別の古いスレッド機能がありました。
43ありました。
4444この古いモデルは問題があることが知られていて、非推奨で、バージョン5.10 で
4545削除されました。
4646できるだけ速やかに既存の5.005スレッドを新しいものに移行することが
4747強く勧められます。
4848
4949=begin original
5050
5151You can see which (or neither) threading flavour you have by
5252running C<perl -V> and looking at the C<Platform> section.
5353If you have C<useithreads=define> you have ithreads, if you
5454have C<use5005threads=define> you have 5.005 threads.
5555If you have neither, you don't have any thread support built in.
5656If you have both, you are in trouble.
5757
5858=end original
5959
6060C<perl -V> で C<Platform> セクションを見れば、どちらのスレッド機能があるのか
6161(あるいは無いのか)を知ることができます。
6262もし C<useithreads=define> となって
6363いればiスレッドをサポートしているし、C<use5005threads=define> とあれば
64645.005 スレッドです。
6565両方とも出ない場合、あなたの Perl はスレッドをサポートしていません。
6666両方ある場合は問題があります。
6767
6868=begin original
6969
7070The L<threads> and L<threads::shared> modules are included in the core Perl
7171distribution. Additionally, they are maintained as a separate modules on
7272CPAN, so you can check there for any updates.
7373
7474=end original
7575
7676L<threads> と L<threads::shared> のモジュールはコア Perl 配布に
7777含まれています。
7878さらに、CPAN では別個のモジュールとして保守されているので、更新については
7979CPAN をチェックできます。
8080
8181=head1 What Is A Thread Anyway?
8282
8383(ところでスレッドって何?)
8484
8585=begin original
8686
8787A thread is a flow of control through a program with a single
8888execution point.
8989
9090=end original
9191
9292スレッドとはプログラム内を通じて一つの実行点を持った制御のフローです。
9393
9494=begin original
9595
9696Sounds an awful lot like a process, doesn't it? Well, it should.
9797Threads are one of the pieces of a process. Every process has at least
9898one thread and, up until now, every process running Perl had only one
9999thread. With 5.8, though, you can create extra threads. We're going
100100to show you how, when, and why.
101101
102102=end original
103103
104104こういうと非常に多くの点でプロセスに似ているように聞こえるでしょう。
105105確かにその通りで、スレッドはひとつのプロセスにおける細かい部分の一つです。
106106全てのプロセスは少なくとも一つのスレッドを持ちます。
107107そしてこれまでは、Perl を走らせるプロセスは全てただ一つのスレッドを
108108持っていました。
109109しかし 5.8 になって、余分にスレッドをつくることができるようになりました。
110110それがいつどのように、いかにしてなされるのかをこれから示していきましょう。
111111
112112=head1 Threaded Program Models
113113
114114(スレッドプログラムのモデル)
115115
116116=begin original
117117
118118There are three basic ways that you can structure a threaded
119119program. Which model you choose depends on what you need your program
120120to do. For many non-trivial threaded programs, you'll need to choose
121121different models for different pieces of your program.
122122
123123=end original
124124
125125スレッドプログラムを構築する 3 つの基本的な方法があります。
126126どのモデルを選ぶかはプログラムに何をやらせるかに依存します。
127127多くの重要なスレッドプログラムにおいては、プログラム中の異なる部分に
128128異なるモデルを選択する必要があるでしょう。
129129
130130=head2 Boss/Worker
131131
132132(ボス/ワーカー)
133133
134134=begin original
135135
136136The boss/worker model usually has one I<boss> thread and one or more
137137I<worker> threads. The boss thread gathers or generates tasks that need
138138to be done, then parcels those tasks out to the appropriate worker
139139thread.
140140
141141=end original
142142
143143ボス・ワーカーモデルでは通常、一つの I<ボス> スレッドと、一つ以上の
144144I<ワーカー> スレッドを持ります。
145ボススレッドは必要とされるタスクを集約ないし生成します
145ボススレッドは必要とされるタスクを集約ないし生成します; それからそれらの
146それからそれらのタスクを適したワーカースレッドに分配します。
146タスクを適したワーカースレッドに分配します。
147147
148148=begin original
149149
150150This model is common in GUI and server programs, where a main thread
151151waits for some event and then passes that event to the appropriate
152152worker threads for processing. Once the event has been passed on, the
153153boss thread goes back to waiting for another event.
154154
155155=end original
156156
157このモデルは GUI とサーバプログラムに共通です
157このモデルは GUI とサーバプログラムに共通です; そこではメインスレッドが
158そこではメンスレッドがイベント発生を待ち、処理のために適した
158イベント発生を待ち、処理のために適したワーカースレッドにイベントを渡します。
159ワーカースレッドにイベントを渡します。
160159ひとたびイベントが渡されると、ボススレッドは次のイベントのために待機します。
161160
162161=begin original
163162
164163The boss thread does relatively little work. While tasks aren't
165164necessarily performed faster than with any other method, it tends to
166165have the best user-response times.
167166
168167=end original
169168
170169ボススレッドは相対的に仕事量は少ないです。
171170タスクは他の方法を使ったものより必ずしも早く実行されるわけではないですが、
172171最もユーザーレスポンスタイムが良くなる傾向にあります。
173172
174173=head2 Work Crew
175174
176175(仕事仲間)
177176
178177=begin original
179178
180179In the work crew model, several threads are created that do
181180essentially the same thing to different pieces of data. It closely
182181mirrors classical parallel processing and vector processors, where a
183182large array of processors do the exact same thing to many pieces of
184183data.
185184
186185=end original
187186
188187仕事仲間モデルでは、データの様々な部分に対し本質的に同じ作業を行う
189188いくつかのスレッドがつくられます。
190189これは、プロセッサの巨大な配列が多くのデータ片に対して全く同じことを行う
191190古典的な並列処理やベクトル処理とそっくりです。
192191
193192=begin original
194193
195194This model is particularly useful if the system running the program
196195will distribute multiple threads across different processors. It can
197196also be useful in ray tracing or rendering engines, where the
198197individual threads can pass on interim results to give the user visual
199198feedback.
200199
201200=end original
202201
203202プログラムを走らせているシステムが、異なるプロセスをまたいでマルチスレッドを
204203分配するような場合、このモデルは殊のほか便利です。
205204また、レイトレースやレンダリングエンジンといった、個々のスレッドが暫定的な
206205結果をユーザに対し視覚的にフィードバックするような場合にも便利でしょう。
207206
208207=head2 Pipeline
209208
210209(パイプライン)
211210
212211=begin original
213212
214213The pipeline model divides up a task into a series of steps, and
215214passes the results of one step on to the thread processing the
216215next. Each thread does one thing to each piece of data and passes the
217216results to the next thread in line.
218217
219218=end original
220219
221パイプラインモデルはあるタスクを何段階の処理の連続へと分けます
220パイプラインモデルはあるタスクを何段階の処理の連続へと分けます;
222221そして一つのステップの結果を次の処理を行うスレッドへと渡します。
223222それぞれのスレッドはデータの各部分に対し一つのことを行い、結果を次の
224223スレッドへ渡します。
225224
226225=begin original
227226
228227This model makes the most sense if you have multiple processors so two
229228or more threads will be executing in parallel, though it can often
230229make sense in other contexts as well. It tends to keep the individual
231230tasks small and simple, as well as allowing some parts of the pipeline
232231to block (on I/O or system calls, for example) while other parts keep
233232going. If you're running different parts of the pipeline on different
234233processors you may also take advantage of the caches on each
235234processor.
236235
237236=end original
238237
239238しばしば他の文脈でも同じぐらいの意味があるますが、二つ以上のスレッドが
240239並列に処理を行うようにあなたがマルチプロセッサを持っているならば、この
241240モデルは最も意味があります。
242241それは、あるパイプラインの一部が進行中の間に、他のパイプラインの一部が
243242(例えば I/O やシステムコールを)ブロックするのを
244243許可するのと同様、個々のタスクを小さく単純なものに留める傾向があります。
245244もし違うプロセッサ上で別々のパイプラインを走らせるなら、それぞれの
246245プロセッサのキャッシュを利用するという利益を得ることができるでしょう。
247246
248247=begin original
249248
250249This model is also handy for a form of recursive programming where,
251250rather than having a subroutine call itself, it instead creates
252251another thread. Prime and Fibonacci generators both map well to this
253252form of the pipeline model. (A version of a prime number generator is
254253presented later on.)
255254
256255=end original
257256
258257このモデルはまた、自分自身を呼び出すサブルーチンを持つよりも、別の
259258スレッドを生み出すような再起的プログラムの形態に利用しやすいです。
260259素数やフィボナッチ数列ジェネレーターは、どちらもこのパイプラインモデルの
261形態にうまく位置付けられます(素数ジェネレーターの例は後で登場します)
260形態にうまく位置付けられます。
261(素数ジェネレーターの例は後で登場します。)
262262
263263=head1 What kind of threads are Perl threads?
264264
265265(Perlスレッドはどんなスレッドか?)
266266
267267=begin original
268268
269269If you have experience with other thread implementations, you might
270270find that things aren't quite what you expect. It's very important to
271271remember when dealing with Perl threads that I<Perl Threads Are Not X
272272Threads> for all values of X. They aren't POSIX threads, or
273273DecThreads, or Java's Green threads, or Win32 threads. There are
274274similarities, and the broad concepts are the same, but if you start
275275looking for implementation details you're going to be either
276276disappointed or confused. Possibly both.
277277
278278=end original
279279
280280もしもあなたが他のスレッドの実装を経験したことがあるなら、事態は全く
281281あなたの予想とは違うことがわかるでしょう。
282282Perl スレッドを扱う時には、あらゆる X に対して
283283I<Perl スレッドは X スレッドではない> ということを忘れてはなりません。
284それらは POSIX スレッドではありません
284それらは POSIX スレッドではありません; DecThread でもなければ Java の
285DecThread でもなければ Java のグリーンスレッドでないし、
285グリーンスレッドでないし、Win32 スレッドでもありません。
286Win32 スレッドでもりません。
286類似点はるし、広義の概念は同じです; しかし実装の詳細を調べだしたら、
287類似点はあるし、広義概念は同じ
287なたは失望すか混乱するかどちらかになるしょう
288だが実装の詳細を調べだしたら、あなたは失望するか混乱するかの
289どちらかになるでしょう。
290288あるいはその両方かもしれません。
291289
292290=begin original
293291
294292This is not to say that Perl threads are completely different from
295everything that's ever come before -- they're not. Perl's threading
293everything that's ever come before. They're not. Perl's threading
296294model owes a lot to other thread models, especially POSIX. Just as
297295Perl is not C, though, Perl threads are not POSIX threads. So if you
298296find yourself looking for mutexes, or thread priorities, it's time to
299297step back a bit and think about what you want to do and how Perl can
300298do it.
301299
302300=end original
303301
304302これは、これまで登場してきたあらゆるスレッドと Perl スレッドが完全に
305303異なるということを言っているのではありません。
304そうではありません。
306305Perl スレッドは他のモデル、特に POSIX スレッドに多くを負っています。
307306ですが、Perl が C ではないように、Perl スレッドは POSIX スレッドでは
308307ありません。
309308だから、もしあなたがミューテックスやスレッドプライオリティを
310309期待しているならば、ちょっと立ち戻って、自分が何をしたいのか、
311310Perl はいかにしてそれが可能なのかを考える時です。
312311
313312=begin original
314313
315314However, it is important to remember that Perl threads cannot magically
316315do things unless your operating system's threads allow it. So if your
317316system blocks the entire process on C<sleep()>, Perl usually will, as well.
318317
319318=end original
320319
321320しかし、あなたのオペレーティングシステムのスレッドが許可しない限り、
322321Perl スレッドが魔法のように何かを行うことはできないことを覚えておきましょう。
323322だからもし、システムが C<sleep()> でプロセスを丸ごとブロックするなら、通常
324323Perl も同様にそうするでしょう。
325324
326325=begin original
327326
328327B<Perl Threads Are Different.>
329328
330329=end original
331330
332B<Perl スレッドは別ものです>
331B<Perl スレッドは別ものです。>
333332
334333=head1 Thread-Safe Modules
335334
336335(スレッドセーフなモジュール)
337336
338337=begin original
339338
340339The addition of threads has changed Perl's internals
341340substantially. There are implications for people who write
342341modules with XS code or external libraries. However, since Perl data is
343342not shared among threads by default, Perl modules stand a high chance of
344343being thread-safe or can be made thread-safe easily. Modules that are not
345344tagged as thread-safe should be tested or code reviewed before being used
346345in production code.
347346
348347=end original
349348
350349スレッドの追加は Perl の内部的な実態を変化させてしまいました。
351350これには XS モジュールや外部ライブラリーを書いている人々も含まれます。
352しかしながら、デフォルトではスレッド間で Perl のデータは共有されません
351しかしながら、デフォルトではスレッド間で Perl のデータは共有されません;
353352そのため Perl モジュールはスレッドセーフであるという機会に恵まれていますし、
354353あるいは容易にスレッドセーフにすることができます。
355354スレッドセーフの札がついていないモジュールは製品版の前にテストされるか
356355コードレビューを受けるべきです。
357356
358357=begin original
359358
360359Not all modules that you might use are thread-safe, and you should
361360always assume a module is unsafe unless the documentation says
362361otherwise. This includes modules that are distributed as part of the
363362core. Threads are a relatively new feature, and even some of the standard
364363modules aren't thread-safe.
365364
366365=end original
367366
368367あなたが使おうとしているモジュールの全てがスレッドセーフというわけでは
369368ないですし、モジュールのドキュメントに安全であると書かれていないならば、
370369常に安全ではないものと仮定するべきです。
371370このことは、コアの一部として配布されているモジュールにもあてはまります。
372371スレッドは比較的新しい機構なので、標準モジュールの中にさえスレッドセーフで
373372ないものがあります。
374373
375374=begin original
376375
377376Even if a module is thread-safe, it doesn't mean that the module is optimized
378377to work well with threads. A module could possibly be rewritten to utilize
379378the new features in threaded Perl to increase performance in a threaded
380379environment.
381380
382381=end original
383382
384383仮にあるモジュールがスレッドセーフであったとしても、そのモジュールが
385384うまく働くように最適化されているということを意味するわけではありません。
386385できるだけスレッド環境でパフォーマンスが向上するように、スレッド化された
387386Perl の新機構を利用するようモジュールを書き直したほうがよいです。
388387
389388=begin original
390389
391390If you're using a module that's not thread-safe for some reason, you
392391can protect yourself by using it from one, and only one thread at all.
393392If you need multiple threads to access such a module, you can use semaphores and
394393lots of programming discipline to control access to it. Semaphores
395394are covered in L</"Basic semaphores">.
396395
397396=end original
398397
399398もしもなんらかの理由でスレッドセーフではないモジュールを使っているならば、
400399ただ一つのスレッドからそれを使うことによって防ぐことができます。
401400そのようなモジュールにアクセスするマルチスレッドが必要ならば、セマフォや
402401アクセスを制御するためのプログラミング原則を用いることができます。
403402セマフォは L</"Basic semaphores"> でカバーしています。
404403
405404=begin original
406405
407406See also L</"Thread-Safety of System Libraries">.
408407
409408=end original
410409
411410L</"Thread-Safety of System Libraries"> も参照してください。
412411
413412=head1 Thread Basics
414413
415414(スレッドの基本)
416415
417416=begin original
418417
419418The L<threads> module provides the basic functions you need to write
420419threaded programs. In the following sections, we'll cover the basics,
421420showing you what you need to do to create a threaded program. After
422421that, we'll go over some of the features of the L<threads> module that
423422make threaded programming easier.
424423
425424=end original
426425
427426L<threads> モジュールは、あなたがスレッドプログラムを書くのに必要と
428427なる基本的な機能を提供します。
429428次からのセクションでは、スレッドプログラムを作るのに必要なことを示しながら
430429基礎的なところをカバーしていきましょう。
431430その後で、スレッドプログラミングを容易にしてくれる L<threads> モジュールの
432431機能をみることにします。
433432
434433=head2 Basic Thread Support
435434
436435(基本的なスレッドのサポート)
437436
438437=begin original
439438
440Thread support is a Perl compile-time option -- it's something that's
439Thread support is a Perl compile-time option. It's something that's
441440turned on or off when Perl is built at your site, rather than when
442441your programs are compiled. If your Perl wasn't compiled with thread
443442support enabled, then any attempt to use threads will fail.
444443
445444=end original
446445
447スレッドのサポートは、あなたプログラムがコンパイルされる時ではなく、
446スレッドのサポートは Perl のコンパイル時のオプションす。
448Perl のコンパイル時のオプションによります。
447つまり、あなたプログラムがコンパイルされるではなく、
449つまり、Perl をビルトするときに、サポートのオン・オフを行います。
448Perl をビルトするときに、サポートのオン・オフを行います。
450449スレッドがサポートされるように Perl がコンパイルされていないなら、スレッドを
451450使おうとしても失敗するでしょう。
452451
453452=begin original
454453
455454Your programs can use the Config module to check whether threads are
456455enabled. If your program can't run without them, you can say something
457456like:
458457
459458=end original
460459
461460スレッドが使用可能かどうかをチェックするために Config モジュールを
462461利用できます。
463462あなたのプログラムがスレッド無しには実行できないなら、次のように記述できます:
464463
465464 use Config;
466 $Config{useithreads} or die('Recompile Perl with threads to run this program.');
465 $Config{useithreads} or
466 die('Recompile Perl with threads to run this program.');
467467
468468=begin original
469469
470470A possibly-threaded program using a possibly-threaded module might
471471have code like this:
472472
473473=end original
474474
475475スレッドを利用するかもしれないモジュールを使うプログラムには、
476476次のようなコードをつけておくとよいでしょう:
477477
478478 use Config;
479479 use MyMod;
480480
481481 BEGIN {
482482 if ($Config{useithreads}) {
483483 # We have threads
484484 require MyMod_threaded;
485485 import MyMod_threaded;
486486 } else {
487487 require MyMod_unthreaded;
488488 import MyMod_unthreaded;
489489 }
490490 }
491491
492492=begin original
493493
494494Since code that runs both with and without threads is usually pretty
495495messy, it's best to isolate the thread-specific code in its own
496496module. In our example above, that's what C<MyMod_threaded> is, and it's
497497only imported if we're running on a threaded Perl.
498498
499499=end original
500500
501501スレッドの有無に関わらず走るようなコードは通常、非常に繁雑なものになるので、
502502スレッド専用のコードはモジュールとして分離しておくのがベストです。
503503上の例では、C<MyMod_threaded> がそれで、スレッド可能な Perl 上で走るときだけ
504504インポートされます。
505505
506506=head2 A Note about the Examples
507507
508508(例に対する注意)
509509
510510=begin original
511511
512512In a real situation, care should be taken that all threads are finished
513513executing before the program exits. That care has B<not> been taken in these
514514examples in the interest of simplicity. Running these examples I<as is> will
515515produce error messages, usually caused by the fact that there are still
516516threads running when the program exits. You should not be alarmed by this.
517517
518518=end original
519519
520520実際の状況では、プログラムが終了する前に全てのスレッドが実行を終えることに
521521注意を払わなければなりません。
522522簡明さを重視しているのでここで取り上げる例においては、そのような注意を
523523払って B<いません>。
524524これらの例を I<そのまま> 実行すると、プログラムが終了する際にまだスレッドが
525525走っているという理由で常にエラーメッセージが出力されるでしょう。
526526この警告は気にしなくて良いです。
527527
528528=head2 Creating Threads
529529
530530(スレッドの生成)
531531
532532=begin original
533533
534534The L<threads> module provides the tools you need to create new
535535threads. Like any other module, you need to tell Perl that you want to use
536536it; C<use threads;> imports all the pieces you need to create basic
537537threads.
538538
539539=end original
540540
541541L<threads> モジュールは新たなスレッドを生成するのに必要なツールを提供します。
542542他のモジュール同様、それを使いたいと Perl に伝える必要があります;
543543C<use threads;> によって基本的なスレッドを生み出すのに必要な全ての部品が
544544インポートされます。
545545
546546=begin original
547547
548548The simplest, most straightforward way to create a thread is with C<create()>:
549549
550550=end original
551551
552552最も単純で直接的なスレッドの生成方法は C<create()> によるものです:
553553
554554 use threads;
555555
556556 my $thr = threads->create(\&sub1);
557557
558558 sub sub1 {
559559 print("In the thread\n");
560560 }
561561
562562=begin original
563563
564564The C<create()> method takes a reference to a subroutine and creates a new
565565thread that starts executing in the referenced subroutine. Control
566566then passes both to the subroutine and the caller.
567567
568568=end original
569569
570570C<create()> メソッドはサブルーチンへのリファレンスを引数にとって新しい
571スレッドを生成します
571スレッドを生成します; このスレッドはリファレンスされたサブルーチンの実行を
572このスレッドはリファレンスされたサブルーチンの実行を開始します。
572開始します。
573573このとき制御はサブルーチンと呼び出し側との両方に渡されます。
574574
575575=begin original
576576
577577If you need to, your program can pass parameters to the subroutine as
578578part of the thread startup. Just include the list of parameters as
579579part of the C<threads-E<gt>create()> call, like this:
580580
581581=end original
582582
583583もし必要ならばスレッド開始時のサブルーチンにパラメータを渡せます。
584584以下のように、C<threads-E<gt>create()> の呼び出しにパラメータのリストを
585585含めます:
586586
587587 use threads;
588588
589589 my $Param3 = 'foo';
590590 my $thr1 = threads->create(\&sub1, 'Param 1', 'Param 2', $Param3);
591591 my @ParamList = (42, 'Hello', 3.14);
592592 my $thr2 = threads->create(\&sub1, @ParamList);
593593 my $thr3 = threads->create(\&sub1, qw(Param1 Param2 Param3));
594594
595595 sub sub1 {
596596 my @InboundParameters = @_;
597597 print("In the thread\n");
598 print('Got parameters >', join('<>', @InboundParameters), "<\n");
598 print('Got parameters >', join('<>',@InboundParameters), "<\n");
599599 }
600600
601601=begin original
602602
603603The last example illustrates another feature of threads. You can spawn
604604off several threads using the same subroutine. Each thread executes
605605the same subroutine, but in a separate thread with a separate
606606environment and potentially separate arguments.
607607
608608=end original
609609
610610最後の例はスレッドのもう一つの特徴を示しています。
611611同じサブルーチンを利用するいくつものスレッドを生成することができます。
612612それぞれのスレッドは同一のサブルーチンを実行するが、それぞれのスレッドは
613613それぞれ別々の環境と引数をとることができます。
614614
615615=begin original
616616
617617C<new()> is a synonym for C<create()>.
618618
619619=end original
620620
621621C<new()> は C<create()> の言い換えです。
622622
623623=head2 Waiting For A Thread To Exit
624624
625625(スレッド終了の待機)
626626
627627=begin original
628628
629629Since threads are also subroutines, they can return values. To wait
630630for a thread to exit and extract any values it might return, you can
631631use the C<join()> method:
632632
633633=end original
634634
635635スレッドはサブルーチンでもあるので、値を返せます。
636636スレッドが終了して何らかの戻り値を得るのを待つために、C<join()> を使えます:
637637
638638 use threads;
639639
640640 my ($thr) = threads->create(\&sub1);
641641
642642 my @ReturnData = $thr->join();
643643 print('Thread returned ', join(', ', @ReturnData), "\n");
644644
645645 sub sub1 { return ('Fifty-six', 'foo', 2); }
646646
647647=begin original
648648
649649In the example above, the C<join()> method returns as soon as the thread
650650ends. In addition to waiting for a thread to finish and gathering up
651651any values that the thread might have returned, C<join()> also performs
652652any OS cleanup necessary for the thread. That cleanup might be
653653important, especially for long-running programs that spawn lots of
654654threads. If you don't want the return values and don't want to wait
655655for the thread to finish, you should call the C<detach()> method
656656instead, as described next.
657657
658658=end original
659659
660660上の例では、スレッドが終了するとすぐに C<join()> メソッドが戻ります。
661661スレッドの終了と、返すべき値を収集するための待機に加えて、C<join()> は
662662スレッドが必要とする OS レベルのクリーンナップを実行します。
663663このクリーンナップは重要です; 特に長時間にわたって実行されるプログラムが
664664大量のスレッドを生成する場合には。
665665もしも戻り値を必要とせず、スレッドの終了を待つ必要もなければ、かわりに
666666次に説明する C<detach()> メソッドを呼び出すべきです。
667667
668668=begin original
669669
670670NOTE: In the example above, the thread returns a list, thus necessitating
671671that the thread creation call be made in list context (i.e., C<my ($thr)>).
672See L<threads/"$thr->join()"> and L<threads/"THREAD CONTEXT"> for more
672See L<< threads/"$thr->join()" >> and L<threads/"THREAD CONTEXT"> for more
673673details on thread context and return values.
674674
675675=end original
676676
677677注意: 上記の例では、スレッドはリストを返すので、スレッド作成呼び出しは
678678(C<my ($thr)> のように)リストコンテキストで行われる必要があります。
679679スレッドのコンテキストと返り値に関する更なる詳細については
680L<threads/"$thr->join()"> と L<threads/"THREAD CONTEXT"> を参照してください。
680L<< threads/"$thr->join()" >> と L<threads/"THREAD CONTEXT"> を
681参照してください。
681682
682683=head2 Ignoring A Thread
683684
684685(スレッドを無視する)
685686
686687=begin original
687688
688689C<join()> does three things: it waits for a thread to exit, cleans up
689690after it, and returns any data the thread may have produced. But what
690691if you're not interested in the thread's return values, and you don't
691692really care when the thread finishes? All you want is for the thread
692693to get cleaned up after when it's done.
693694
694695=end original
695696
696C<join()> は三つのことを行います
697C<join()> は三つのことを行います: スレッド終了の待機、その後の
697スレッド終了の待機、その後のクリーンナップ、そしてスレッドが生み出したで
698クリーンナップ、そしてスレッドが生み出したであろうデータを返すことです。
698あろうデータを返すことです。
699699しかし、スレッドの返す値に関心がなく、いつスレッドが終了するのかを本当に
700700気にしない場合には?
701701必要なのは仕事がなされた後にスレッドがクリーンナップされることです。
702702
703703=begin original
704704
705705In this case, you use the C<detach()> method. Once a thread is detached,
706706it'll run until it's finished; then Perl will clean up after it
707707automatically.
708708
709709=end original
710710
711711このような場合、C<detach()> メソッドを使います。
712712ひとたびスレッドが detach されると、スレッドは終了するまで実行し続け、
713713そのあと Perl が自動的にクリーンナップを行います。
714714
715715 use threads;
716716
717717 my $thr = threads->create(\&sub1); # Spawn the thread
718718
719719 $thr->detach(); # Now we officially don't care any more
720720
721721 sleep(15); # Let thread run for awhile
722722
723723 sub sub1 {
724 $a = 0;
724 my $count = 0;
725725 while (1) {
726 $a++;
726 $count++;
727 print("\$a is $a\n");
727 print("\$count is $count\n");
728728 sleep(1);
729729 }
730730 }
731731
732732=begin original
733733
734734Once a thread is detached, it may not be joined, and any return data
735735that it might have produced (if it was done and waiting for a join) is
736736lost.
737737
738738=end original
739739
740一度あるスレッドが detach されたら、そのスレッドは join されないでしょう
740一度あるスレッドが detach されたら、そのスレッドは join されないでしょう;
741741(join のために待機しても)スレッドが生成したであろうデータは失われます。
742742
743743=begin original
744744
745745C<detach()> can also be called as a class method to allow a thread to
746746detach itself:
747747
748748=end original
749749
750750C<detach()> はスレッドが自分自身を detach するためにクラスメソッドとしても
751751呼び出されます:
752752
753753 use threads;
754754
755755 my $thr = threads->create(\&sub1);
756756
757757 sub sub1 {
758758 threads->detach();
759759 # Do more work
760760 }
761761
762762=head2 Process and Thread Termination
763763
764764(プロセスとスレッドの終了)
765765
766766=begin original
767767
768768With threads one must be careful to make sure they all have a chance to
769769run to completion, assuming that is what you want.
770770
771771=end original
772772
773773スレッドを使う場合は、全てのスレッドが確実に完全に実行される(それが
774774あなたの望むもののはずです)ように注意しなければなりません。
775775
776776=begin original
777777
778778An action that terminates a process will terminate I<all> running
779779threads. die() and exit() have this property,
780780and perl does an exit when the main thread exits,
781781perhaps implicitly by falling off the end of your code,
782782even if that's not what you want.
783783
784784=end original
785785
786786プロセスを終了させる行動は実行中の I<全ての> スレッドを終了させます。
787787die() と exit() はこの性質を持ち、(あなたが望んでいないとしても)
788788おそらくは暗黙のうちにコードの最後に到達することによってメインスレッドが
789789終了すると、perl は終了します。
790790
791791=begin original
792792
793793As an example of this case, this code prints the message
794794"Perl exited with active threads: 2 running and unjoined":
795795
796796=end original
797797
798798この場合の例として、このコードは
799799"Perl exited with active threads: 2 running and unjoined" というメッセージを
800800表示します:
801801
802802 use threads;
803803 my $thr1 = threads->new(\&thrsub, "test1");
804804 my $thr2 = threads->new(\&thrsub, "test2");
805805 sub thrsub {
806806 my ($message) = @_;
807807 sleep 1;
808808 print "thread $message\n";
809809 }
810810
811811=begin original
812812
813813But when the following lines are added at the end:
814814
815815=end original
816816
817817しかし以下の行が最後に追加されると:
818818
819819 $thr1->join();
820820 $thr2->join();
821821
822822=begin original
823823
824824it prints two lines of output, a perhaps more useful outcome.
825825
826826=end original
827827
8288282 行の出力があり、おそらくより有用な成果となります。
829829
830830=head1 Threads And Data
831831
832832(スレッドとデータ)
833833
834834=begin original
835835
836836Now that we've covered the basics of threads, it's time for our next
837837topic: Data. Threading introduces a couple of complications to data
838838access that non-threaded programs never need to worry about.
839839
840840=end original
841841
842これでスレッドの基本部分については見終わりました。
842これでスレッドの基本部分については見終わりました; 次の話題はデータです
843次の話題はデータです。
844843スレッドを扱うと、非スレッドプログラムが決して心配することのなかった
845844データアクセスに対する二つの複雑さを導入することになります。
846845
847846=head2 Shared And Unshared Data
848847
849848(共有データと非共有データ)
850849
851850=begin original
852851
853852The biggest difference between Perl I<ithreads> and the old 5.005 style
854853threading, or for that matter, to most other threading systems out there,
855854is that by default, no data is shared. When a new Perl thread is created,
856855all the data associated with the current thread is copied to the new
857856thread, and is subsequently private to that new thread!
858This is similar in feel to what happens when a UNIX process forks,
857This is similar in feel to what happens when a Unix process forks,
859858except that in this case, the data is just copied to a different part of
860859memory within the same process rather than a real fork taking place.
861860
862861=end original
863862
864863I<iスレッド> と古い 5.005 型スレッドの間の(もっといえば、そこから外れる
865864多くのスレッドシステムにとっての)最大の違いは、デフォルトではデータが
866865共有されないという点です。
867866新しい Perl スレッドが生成されるとき、現在のスレッドに関連する全てのデータは
868新しいスレッドにコピーされます
867新しいスレッドにコピーされます; 続いてそのデータは新しいスレッド内で
869続いてそのデータは新しいスレッド内でプライベートなものとなります!
868プライベートなものとなります!
870これは UNIX のプロセスが fork するときに起きることと似ています
869これは Unix のプロセスが fork するときに起きることと似ています;
871870ただしこの場合、実際の fork ではメモリ上での置き換えが起こるのに対して、この
872871データは同一プロセッサ内の違うメモリ部分にコピーされるだけであるという点が
873872除かれます。
874873
875874=begin original
876875
877876To make use of threading, however, one usually wants the threads to share
878877at least some data between themselves. This is done with the
879878L<threads::shared> module and the C<:shared> attribute:
880879
881880=end original
882881
883882しかしスレッド機能を利用するならば、通常はスレッド間で少なくともいくつかの
884883データを共有したいものです。
885884これは L<threads::shared> モジュールと C<:shared> 属性によって行われます:
886885
887886 use threads;
888887 use threads::shared;
889888
890889 my $foo :shared = 1;
891890 my $bar = 1;
892891 threads->create(sub { $foo++; $bar++; })->join();
893892
894893 print("$foo\n"); # Prints 2 since $foo is shared
895894 print("$bar\n"); # Prints 1 since $bar is not shared
896895
897896=begin original
898897
899898In the case of a shared array, all the array's elements are shared, and for
900899a shared hash, all the keys and values are shared. This places
901900restrictions on what may be assigned to shared array and hash elements: only
902901simple values or references to shared variables are allowed - this is
903902so that a private variable can't accidentally become shared. A bad
904903assignment will cause the thread to die. For example:
905904
906905=end original
907906
908共有化された配列の場合は、配列の要素全てが共有化されます
907共有化された配列の場合は、配列の要素全てが共有化されます;
909908共有化されたハッシュの場合、全てのキーと値が共有されます。
910909共有化された配列やハッシュの要素に代入するものに対しては制限があります:
911単純な値や共有化された変数へのリファレンスは可能です
910単純な値や共有化された変数へのリファレンスは可能です - これは、
912これは、プライベート変数が図らずも共有化されることがないからです。
911プライベート変数が図らずも共有化されることがないからです。
913912不正な代入はスレッドを殺してしまうでしょう。
914913例えば:
915914
916915 use threads;
917916 use threads::shared;
918917
919918 my $var = 1;
920919 my $svar :shared = 2;
921920 my %hash :shared;
922921
923922 ... create some threads ...
924923
925924=begin original
926925
927 $hash{a} = 1; # All threads see exists($hash{a}) and $hash{a} == 1
926 $hash{a} = 1; # All threads see exists($hash{a})
927 # and $hash{a} == 1
928928 $hash{a} = $var; # okay - copy-by-value: same effect as previous
929929 $hash{a} = $svar; # okay - copy-by-value: same effect as previous
930930 $hash{a} = \$svar; # okay - a reference to a shared variable
931931 $hash{a} = \$var; # This will die
932932 delete($hash{a}); # okay - all threads will see !exists($hash{a})
933933
934934=end original
935935
936 $hash{a} = 1; # どのスレッドからも exists($hash{a}) and $hash{a} == 1
936 $hash{a} = 1; # どのスレッドからも exists($hash{a})
937 $hash{a} = $var; # OK、値のコピー。効果は上に同じ。
937 # and $hash{a} == 1
938 $hash{a} = $svar; # OK、値のコピー効果は上に同じ
938 $hash{a} = $var; # OK、値のコピー: 効果は上に同じ
939 $hash{a} = \$svar; # OK、共有変数へリファレンス。
939 $hash{a} = $svar; # OK、コピー: 効果は上に同じ
940 $hash{a} = \$svar; # OK、共有変数へのリファレンス
940941 $hash{a} = \$var; # これは die する
941942 delete($hash{a}); # OK、どのスレッドからも !exists($hash{a})
942943
943944=begin original
944945
945946Note that a shared variable guarantees that if two or more threads try to
946947modify it at the same time, the internal state of the variable will not
947948become corrupted. However, there are no guarantees beyond this, as
948949explained in the next section.
949950
950951=end original
951952
952953共有変数が、複数のスレッドが同時にその変数に変更を加えようとしても、
953954変数の内部状態は破壊されないことを保証していることに注意してください。
954955しかし次のセクションで説明するように、ここを超えてしまうと保証は
955956なくなってしまいます。
956957
957958=head2 Thread Pitfalls: Races
958959
959960(スレッドの落とし穴: 競合)
960961
961962=begin original
962963
963964While threads bring a new set of useful tools, they also bring a
964965number of pitfalls. One pitfall is the race condition:
965966
966967=end original
967968
968969スレッドは新しい便利なツールを一揃いもたらしてくれる一方で、たくさんの
969970落とし穴ももたらします。
970971その一つは競合条件です:
971972
972973 use threads;
973974 use threads::shared;
974975
975 my $a :shared = 1;
976 my $x :shared = 1;
976977 my $thr1 = threads->create(\&sub1);
977978 my $thr2 = threads->create(\&sub2);
978979
979980 $thr1->join();
980981 $thr2->join();
981 print("$a\n");
982 print("$x\n");
982983
983 sub sub1 { my $foo = $a; $a = $foo + 1; }
984 sub sub1 { my $foo = $x; $x = $foo + 1; }
984 sub sub2 { my $bar = $a; $a = $bar + 1; }
985 sub sub2 { my $bar = $x; $x = $bar + 1; }
985986
986987=begin original
987988
988What do you think C<$a> will be? The answer, unfortunately, is I<it
989What do you think C<$x> will be? The answer, unfortunately, is I<it
989depends>. Both C<sub1()> and C<sub2()> access the global variable C<$a>, once
990depends>. Both C<sub1()> and C<sub2()> access the global variable C<$x>, once
990991to read and once to write. Depending on factors ranging from your
991992thread implementation's scheduling algorithm to the phase of the moon,
992C<$a> can be 2 or 3.
993C<$x> can be 2 or 3.
993994
994995=end original
995996
996C<$a> はどうなるでしょうか?
997C<$x> はどうなるでしょうか?
997998残念ながら、その答えは I<場合によりけり> です。
998999C<sub1()> と C<sub2()> はどちらも一度だけ読み込み、一度だけ書き込むために
999グローバル変数 C<$a> にアクセスします。
1000グローバル変数 C<$x> にアクセスします。
10001001あなたの使っているスレッド実装のスケジューリングアルゴリズムから月の
1001満ち欠けまでの種々の要因によって、C<$a> は 2 にも 3 にもなりえます。
1002満ち欠けまでの種々の要因によって、C<$x> は 2 にも 3 にもなりえます。
10021003
10031004=begin original
10041005
10051006Race conditions are caused by unsynchronized access to shared
10061007data. Without explicit synchronization, there's no way to be sure that
10071008nothing has happened to the shared data between the time you access it
10081009and the time you update it. Even this simple code fragment has the
10091010possibility of error:
10101011
10111012=end original
10121013
10131014競合条件は共有データに対して非同期なアクセスを行うことによって生じます。
10141015明示的に同期をとらない限り、アクセスして更新するまでの間に
10151016共有データに何も起こらないことを確実にする方法はありません。
10161017こんな単純なコードでさえ、エラーの可能性があります:
10171018
10181019 use threads;
1019 my $a :shared = 2;
1020 my $x :shared = 2;
1020 my $b :shared;
1021 my $y :shared;
1021 my $c :shared;
1022 my $z :shared;
1022 my $thr1 = threads->create(sub { $b = $a; $a = $b + 1; });
1023 my $thr1 = threads->create(sub { $y = $x; $x = $y + 1; });
1023 my $thr2 = threads->create(sub { $c = $a; $a = $c + 1; });
1024 my $thr2 = threads->create(sub { $z = $x; $x = $z + 1; });
10241025 $thr1->join();
10251026 $thr2->join();
10261027
10271028=begin original
10281029
1029Two threads both access C<$a>. Each thread can potentially be interrupted
1030Two threads both access C<$x>. Each thread can potentially be interrupted
1030at any point, or be executed in any order. At the end, C<$a> could be 3
1031at any point, or be executed in any order. At the end, C<$x> could be 3
1031or 4, and both C<$b> and C<$c> could be 2 or 3.
1032or 4, and both C<$y> and C<$z> could be 2 or 3.
10321033
10331034=end original
10341035
1035二つのスレッドが C<$a> にアクセスします。
1036二つのスレッドが C<$x> にアクセスします。
10361037それぞれのスレッドはいずれかの時点で割り込まれたり、いずれかの順番で
10371038実行される可能性があります。
1038結局、C<$a> は 3 か 4 に、C<$b> と C<$c> はともに 2 か 3 になるでしょう。
1039結局、C<$x> は 3 か 4 に、C<$y> と C<$z> はともに 2 か 3 になるでしょう。
10391040
10401041=begin original
10411042
1042Even C<$a += 5> or C<$a++> are not guaranteed to be atomic.
1043Even C<$x += 5> or C<$x++> are not guaranteed to be atomic.
10431044
10441045=end original
10451046
1046C<$a += 5> や C<$a++> でさえ、アトミックな演算であることを保証されません。
1047C<$x += 5> や C<$x++> でさえ、アトミックな演算であることを保証されません。
10471048
10481049=begin original
10491050
10501051Whenever your program accesses data or resources that can be accessed
10511052by other threads, you must take steps to coordinate access or risk
10521053data inconsistency and race conditions. Note that Perl will protect its
10531054internals from your race conditions, but it won't protect you from you.
10541055
10551056=end original
10561057
10571058他のスレッドによってアクセスされる可能性のあるデータやリソースにあなたの
10581059プログラムがアクセスするときはいつでも、整合的なアクセスのための手順を
10591060踏まなければなりません。
10601061さもなければデータの一貫性が崩れたり、競合条件に陥るリスクを
10611062負うことになります。
10621063
10631064=head1 Synchronization and control
10641065
10651066(同期と制御)
10661067
10671068=begin original
10681069
10691070Perl provides a number of mechanisms to coordinate the interactions
10701071between themselves and their data, to avoid race conditions and the like.
10711072Some of these are designed to resemble the common techniques used in thread
10721073libraries such as C<pthreads>; others are Perl-specific. Often, the
10731074standard techniques are clumsy and difficult to get right (such as
10741075condition waits). Where possible, it is usually easier to use Perlish
10751076techniques such as queues, which remove some of the hard work involved.
10761077
10771078=end original
10781079
10791080競合条件やそれに似た状態を回避するために、スレッドとデータとの間の相互作用を
10801081調整する多くのメカニズムを Perl は提供します。
10811082それらのうちのあるものは、C<pthreads> のようなスレッドライブラリにおいて
1082使われる共通のテクニックに似た設計がなされています
1083使われる共通のテクニックに似た設計がなされています; またあるものは Perl に
1083またあるものは Perl に特化しています。
1084特化しています。
10841085しばしば標準的なテクニックというものはぎこちないもので、正しく扱うには
10851086難しいです。
10861087可能なところでは通常、キューのような Perl 的テクニックはより簡単で、難しい
10871088仕事のうちのあるものを取り除いてくれます。
10881089
10891090=head2 Controlling access: lock()
10901091
10911092(アクセス制御:lock())
10921093
10931094=begin original
10941095
10951096The C<lock()> function takes a shared variable and puts a lock on it.
10961097No other thread may lock the variable until the variable is unlocked
10971098by the thread holding the lock. Unlocking happens automatically
10981099when the locking thread exits the block that contains the call to the
10991100C<lock()> function. Using C<lock()> is straightforward: This example has
11001101several threads doing some calculations in parallel, and occasionally
11011102updating a running total:
11021103
11031104=end original
11041105
11051106C<lock()> 関数は共有変数を引数にとり、それにロックをかけます。
11061107ロックを保持するスレッドによって変数のロックが解除されるまで、他のスレッドは
11071108ロックをかけることができません。
11081109ロックしているスレッドが C<lock()> 関数の呼び出しを含むブロックの外に出ると
11091110ロックは自動的に解除されます。
1110C<lock()> の利用は率直なやり方です
1111C<lock()> の利用は率直なやり方です: この例は、ある計算を並列的に処理し、
1111この例は、ある計算を並列的に処理し、時折その総計値を更新するいくつかの
1112時折その総計値を更新するいくつかのスレッドを伴っています:
1112スレッドを伴っています:
11131113
11141114 use threads;
11151115 use threads::shared;
11161116
11171117 my $total :shared = 0;
11181118
11191119 sub calc {
11201120 while (1) {
11211121 my $result;
11221122 # (... do some calculations and set $result ...)
11231123 {
11241124 lock($total); # Block until we obtain the lock
11251125 $total += $result;
11261126 } # Lock implicitly released at end of scope
11271127 last if $result == 0;
11281128 }
11291129 }
11301130
11311131 my $thr1 = threads->create(\&calc);
11321132 my $thr2 = threads->create(\&calc);
11331133 my $thr3 = threads->create(\&calc);
11341134 $thr1->join();
11351135 $thr2->join();
11361136 $thr3->join();
11371137 print("total=$total\n");
11381138
11391139=begin original
11401140
11411141C<lock()> blocks the thread until the variable being locked is
11421142available. When C<lock()> returns, your thread can be sure that no other
11431143thread can lock that variable until the block containing the
11441144lock exits.
11451145
11461146=end original
11471147
11481148ロックされている変数が利用可能になるまで、C<lock()> はそのスレッドを
11491149ブロックします。
11501150C<lock()> が戻ってくると、そのロックが存在しているブロックの外に出ない限り、
11511151他のスレッドがその変数をロックできないことが確実になります。
11521152
11531153=begin original
11541154
11551155It's important to note that locks don't prevent access to the variable
11561156in question, only lock attempts. This is in keeping with Perl's
11571157longstanding tradition of courteous programming, and the advisory file
11581158locking that C<flock()> gives you.
11591159
11601160=end original
11611161
11621162ロックは問題の変数にアクセスするのを阻止するのではなくて、ロックの試みを
11631163阻止するということに注意することが重要です。
11641164これは Perl の長年にわたる作法どおりのプログラミングの伝統と、flock() が
11651165提供する勧告ロックとに調和するものです。
11661166
11671167=begin original
11681168
11691169You may lock arrays and hashes as well as scalars. Locking an array,
11701170though, will not block subsequent locks on array elements, just lock
11711171attempts on the array itself.
11721172
11731173=end original
11741174
11751175スカラ変数同様、配列やハッシュにもロックをかけるかもしれません。
11761176しかし、配列へのロックは、配列の要素に対する二次的なロックを
11771177ブロックするのではなく、配列そのものへのロックの試みをブロックします。
11781178
11791179=begin original
11801180
11811181Locks are recursive, which means it's okay for a thread to
11821182lock a variable more than once. The lock will last until the outermost
11831183C<lock()> on the variable goes out of scope. For example:
11841184
11851185=end original
11861186
11871187ロックは再帰的、つまりスレッドはある変数に対し何度もロックをかけて大丈夫です。
11881188一番外側の C<lock()> がスコープを抜けるまでロックは続きます。
11891189例えば:
11901190
11911191 my $x :shared;
11921192 doit();
11931193
11941194 sub doit {
11951195 {
11961196 {
11971197 lock($x); # Wait for lock
11981198 lock($x); # NOOP - we already have the lock
11991199 {
12001200 lock($x); # NOOP
12011201 {
12021202 lock($x); # NOOP
12031203 lockit_some_more();
12041204 }
12051205 }
12061206 } # *** Implicit unlock here ***
12071207 }
12081208 }
12091209
12101210 sub lockit_some_more {
12111211 lock($x); # NOOP
12121212 } # Nothing happens here
12131213
12141214=begin original
12151215
12161216Note that there is no C<unlock()> function - the only way to unlock a
12171217variable is to allow it to go out of scope.
12181218
12191219=end original
12201220
1221C<unlock()> 関数は無いことに注意してください
1221C<unlock()> 関数は無いことに注意してください - 変数のロックを解除する方法は
1222変数のロックを解除する方法はスコープを抜けさせることだけです。
1222スコープを抜けさせることだけです。
12231223
12241224=begin original
12251225
12261226A lock can either be used to guard the data contained within the variable
12271227being locked, or it can be used to guard something else, like a section
12281228of code. In this latter case, the variable in question does not hold any
12291229useful data, and exists only for the purpose of being locked. In this
12301230respect, the variable behaves like the mutexes and basic semaphores of
12311231traditional thread libraries.
12321232
12331233=end original
12341234
12351235ロックされている変数内に保持されているデータをガードするか、あるいは
12361236コードのセクションのようなものを守るために、ロックは用いられます。
12371237後者の場合、問題の変数は役に立つデータを持たず、ロックの目的のためにだけ
12381238存在します。
12391239この点からすると、その変数は伝統的なスレッドライブラリにおける
12401240ミューテックスや基本的なセマフォのような振る舞いをするといえます。
12411241
12421242=head2 A Thread Pitfall: Deadlocks
12431243
12441244(スレッドの落とし穴: デッドロック)
12451245
12461246=begin original
12471247
12481248Locks are a handy tool to synchronize access to data, and using them
12491249properly is the key to safe shared data. Unfortunately, locks aren't
12501250without their dangers, especially when multiple locks are involved.
12511251Consider the following code:
12521252
12531253=end original
12541254
1255ロックはデータに同期アクセスするための便利なツールです
1255ロックはデータに同期アクセスするための便利なツールです; 適切に使えば安全な
1256適切に使えば安全な共有データへの鍵となります。
1256共有データへの鍵となります。
1257残念なことに、ロックには危険が伴います
1257残念なことに、ロックには危険が伴います; 特に複数のロックが関わると
1258特に複数のロックが関わるとそうなります。
1258そうなります。
12591259次のコードを考えてみましょう:
12601260
12611261 use threads;
12621262
1263 my $a :shared = 4;
1263 my $x :shared = 4;
1264 my $b :shared = 'foo';
1264 my $y :shared = 'foo';
12651265 my $thr1 = threads->create(sub {
1266 lock($a);
1266 lock($x);
12671267 sleep(20);
1268 lock($b);
1268 lock($y);
12691269 });
12701270 my $thr2 = threads->create(sub {
1271 lock($b);
1271 lock($y);
12721272 sleep(20);
1273 lock($a);
1273 lock($x);
12741274 });
12751275
12761276=begin original
12771277
12781278This program will probably hang until you kill it. The only way it
12791279won't hang is if one of the two threads acquires both locks
12801280first. A guaranteed-to-hang version is more complicated, but the
12811281principle is the same.
12821282
12831283=end original
12841284
12851285このプログラムは恐らくあなたが kill するまで固まってしまうでしょう。
12861286ハングさせないための唯一の方法は、どちらかのスレッドが先に両方のロックを
12871287獲得することです。
12881288ハングを保証する方法はもっと複雑ですが、原理はこれと同じです。
12891289
12901290=begin original
12911291
1292The first thread will grab a lock on C<$a>, then, after a pause during which
1292The first thread will grab a lock on C<$x>, then, after a pause during which
12931293the second thread has probably had time to do some work, try to grab a
1294lock on C<$b>. Meanwhile, the second thread grabs a lock on C<$b>, then later
1294lock on C<$y>. Meanwhile, the second thread grabs a lock on C<$y>, then later
1295tries to grab a lock on C<$a>. The second lock attempt for both threads will
1295tries to grab a lock on C<$x>. The second lock attempt for both threads will
12961296block, each waiting for the other to release its lock.
12971297
12981298=end original
12991299
1300最初のスレッドが C<$a> のロックを手にします
1300最初のスレッドが C<$x> のロックを手にします; それから二つ目のスレッドが
1301それから二つ目のスレッドが何かやっている間に一時停止した後、C<$b> への
1301何かやっている間に一時停止した後、C<$y> へのロックを手に入れようと試みます。
1302ロックを手に入れようと試みます
1302ところが、その二つ目のスレッドは C<$y> へのロックを手にます; そして
1303ところが、その二つ目のスレッドは C<$b> のロックを手にします。
1303その C<$x> のロックを手に入れようとします。
1304そしてその後 C<$a> のロックを手に入れようとします。
13051304それぞれのスレッドが、他方のスレッドのロックが開放されるの待つため、
13061305二番目のロックへの試みはブロックしてしまいます。
13071306
13081307=begin original
13091308
13101309This condition is called a deadlock, and it occurs whenever two or
13111310more threads are trying to get locks on resources that the others
13121311own. Each thread will block, waiting for the other to release a lock
13131312on a resource. That never happens, though, since the thread with the
13141313resource is itself waiting for a lock to be released.
13151314
13161315=end original
13171316
1318この状態をデッドロックと言います
1317この状態をデッドロックと言います; 二つ以上のスレッドが他スレッドの所有する
1319二つ以上のスレッドが他スレッドの所有するリソースをロックしようと
1318リソースをロックしようと試みるときにはいつでも生じます。
1320試みるときにはいつでも生じます。
13211319他のスレッドがリソースへのロックを開放するのを待って、互いにスレッドが
13221320ブロックします。
13231321しかし、リソースを持っているスレッドが自分自身のロックの開放を待つ場合は
13241322生じません。
13251323
13261324=begin original
13271325
13281326There are a number of ways to handle this sort of problem. The best
13291327way is to always have all threads acquire locks in the exact same
1330order. If, for example, you lock variables C<$a>, C<$b>, and C<$c>, always lock
1328order. If, for example, you lock variables C<$x>, C<$y>, and C<$z>, always lock
1331C<$a> before C<$b>, and C<$b> before C<$c>. It's also best to hold on to locks for
1329C<$x> before C<$y>, and C<$y> before C<$z>. It's also best to hold on to locks for
13321330as short a period of time to minimize the risks of deadlock.
13331331
13341332=end original
13351333
13361334この種の問題を扱う方法はたくさんあります。
13371335最もよい方法は、常に全てのスレッドが正確に同じ順番でロックを獲得するように
13381336することです。
1339例えば、C<$a>、C<$b>、C<$c>をロックするなら、いつでも C<$b> の前に C<$a> を、
1337例えば、C<$x>、C<$y>、C<$z> をロックするなら、いつでも C<$y> の前に C<$x> を、
1340そして C<$c> の前に C<$b> をロックするようにします。
1338そして C<$z> の前に C<$y> をロックするようにします。
1341デッドロックの危険を最小にするために、短い時間だけロックを保持するのも良い手です。
1339デッドロックの危険を最小にするために、短い時間だけロックを保持するのも
1340良い手です。
13421341
13431342=begin original
13441343
13451344The other synchronization primitives described below can suffer from
13461345similar problems.
13471346
13481347=end original
13491348
13501349下記で説明するような他のプリミティブな同期も同様な問題を抱える可能性があります。
13511350
13521351=head2 Queues: Passing Data Around
13531352
13541353(キュー: データの受け渡し)
13551354
13561355=begin original
13571356
13581357A queue is a special thread-safe object that lets you put data in one
13591358end and take it out the other without having to worry about
13601359synchronization issues. They're pretty straightforward, and look like
13611360this:
13621361
13631362=end original
13641363
13651364キューとは、一方の端にデータを入れ、他方から取り出すことによって、
13661365同期の問題を心配しなくてすむ、特別なスレッドセーフオブジェクトです。
13671366これらは非常に素朴で、以下のようなものです:
13681367
13691368 use threads;
13701369 use Thread::Queue;
13711370
13721371 my $DataQueue = Thread::Queue->new();
13731372 my $thr = threads->create(sub {
13741373 while (my $DataElement = $DataQueue->dequeue()) {
13751374 print("Popped $DataElement off the queue\n");
13761375 }
13771376 });
13781377
13791378 $DataQueue->enqueue(12);
13801379 $DataQueue->enqueue("A", "B", "C");
13811380 sleep(10);
13821381 $DataQueue->enqueue(undef);
13831382 $thr->join();
13841383
13851384=begin original
13861385
13871386You create the queue with C<Thread::Queue-E<gt>new()>. Then you can
13881387add lists of scalars onto the end with C<enqueue()>, and pop scalars off
13891388the front of it with C<dequeue()>. A queue has no fixed size, and can grow
13901389as needed to hold everything pushed on to it.
13911390
13921391=end original
13931392
13941393C<Thread::Queue-E<gt>new()> でキューを生成します。
1395それから C<enqueue()> を使ってキューの
1394それから C<enqueue()> を使ってキューの最後にスカラのリストを追加します;
1396最後にスカラのリストを追加します。
13971395そして C<dequeue()> でキューの前方からスカラを取り出します。
1398キューのサイズは固定していません
1396キューのサイズは固定していません; キューの中に押し込められたものを保持する
1399キューの中に押し込められたものを保持する必要に応じてサイズは成長します。
1397必要に応じてサイズは成長します。
14001398
14011399=begin original
14021400
14031401If a queue is empty, C<dequeue()> blocks until another thread enqueues
14041402something. This makes queues ideal for event loops and other
14051403communications between threads.
14061404
14071405=end original
14081406
14091407もしキューが空っぽの場合、他のスレッドが何かをキューの中に入れるまで、
14101408C<dequeue()> はブロックします。
14111409そのため、イベントループやスレッド間でのコミュニケーションにとって、
14121410キューは理想的です。
14131411
14141412=head2 Semaphores: Synchronizing Data Access
14151413
14161414(セマフォ:データアクセスの同期)
14171415
14181416=begin original
14191417
14201418Semaphores are a kind of generic locking mechanism. In their most basic
14211419form, they behave very much like lockable scalars, except that they
14221420can't hold data, and that they must be explicitly unlocked. In their
14231421advanced form, they act like a kind of counter, and can allow multiple
14241422threads to have the I<lock> at any one time.
14251423
14261424=end original
14271425
14281426セマフォは包括的なロックメカニズムの一種です。
14291427最も基本となる形態では、
14301428セマフォはデータを持つことはできないし、明示的にロック解除されなければ
14311429ならないことを除くと、ロック可能なスカラそっくりに振る舞います。
14321430発展的な形態においては、一種のカウンターのように動作し、いつでも複数の
14331431スレッドが I<ロック> を持つことを可能にします。
14341432
14351433=head2 Basic semaphores
14361434
14371435(ベーシックなセマフォ)
14381436
14391437=begin original
14401438
14411439Semaphores have two methods, C<down()> and C<up()>: C<down()> decrements the resource
14421440count, while C<up()> increments it. Calls to C<down()> will block if the
14431441semaphore's current count would decrement below zero. This program
14441442gives a quick demonstration:
14451443
14461444=end original
14471445
1448セマフォは二つのメソッド、C<down()> と C<up()> を持ちます
1446セマフォは二つのメソッド、C<down()> と C<up()> を持ちます: C<down()> は
1449C<down()> はリソースのカウントを減少させ、C<up()> の方は増加させます。
1447リソースのカウントを減少させ、C<up()> の方は増加させます。
14501448セマフォの現在のカウントが 0 を下回るようなら C<down()> の呼び出しは
14511449ブロックします。
14521450このプログラムは短い例です:
14531451
14541452 use threads;
14551453 use Thread::Semaphore;
14561454
14571455 my $semaphore = Thread::Semaphore->new();
14581456 my $GlobalVariable :shared = 0;
14591457
14601458 $thr1 = threads->create(\&sample_sub, 1);
14611459 $thr2 = threads->create(\&sample_sub, 2);
14621460 $thr3 = threads->create(\&sample_sub, 3);
14631461
14641462 sub sample_sub {
14651463 my $SubNumber = shift(@_);
14661464 my $TryCount = 10;
14671465 my $LocalCopy;
14681466 sleep(1);
14691467 while ($TryCount--) {
14701468 $semaphore->down();
14711469 $LocalCopy = $GlobalVariable;
1472 print("$TryCount tries left for sub $SubNumber (\$GlobalVariable is $GlobalVariable)\n");
1470 print("$TryCount tries left for sub $SubNumber "
1471 ."(\$GlobalVariable is $GlobalVariable)\n");
14731472 sleep(2);
14741473 $LocalCopy++;
14751474 $GlobalVariable = $LocalCopy;
14761475 $semaphore->up();
14771476 }
14781477 }
14791478
14801479 $thr1->join();
14811480 $thr2->join();
14821481 $thr3->join();
14831482
14841483=begin original
14851484
14861485The three invocations of the subroutine all operate in sync. The
14871486semaphore, though, makes sure that only one thread is accessing the
14881487global variable at once.
14891488
14901489=end original
14911490
14921491このサブルーチンに対する三つの呼び出しは同時に作用します。
14931492しかし一度に一つのスレッドだけが、グローバル変数にアクセスすることを
14941493セマフォが保証します。
14951494
14961495=head2 Advanced Semaphores
14971496
14981497(高度なセマフォ)
14991498
15001499=begin original
15011500
15021501By default, semaphores behave like locks, letting only one thread
15031502C<down()> them at a time. However, there are other uses for semaphores.
15041503
15051504=end original
15061505
1507デフォルトでは、セマフォはロックのように振舞います
1506デフォルトでは、セマフォはロックのように振舞います; 一度にただ一つの
1508一度にただ一つのスレッドだけが C<down()> できます。
1507スレッドだけが C<down()> できます。
15091508しかし、セマフォには別の使い方があります。
15101509
15111510=begin original
15121511
15131512Each semaphore has a counter attached to it. By default, semaphores are
15141513created with the counter set to one, C<down()> decrements the counter by
15151514one, and C<up()> increments by one. However, we can override any or all
15161515of these defaults simply by passing in different values:
15171516
15181517=end original
15191518
15201519それぞれのセマフォは、関連付けられたカウンタを持ちます。
1521デフォルトでセマフォは生成時、カウンタに 1 がセットされます
1520デフォルトでセマフォは生成時、カウンタに 1 がセットされます; C<down()> は
1522C<down()> はカウンタから 1 を引き、C<up()> は 1 を足します。
1521カウンタから 1 を引き、C<up()> は 1 を足します。
15231522しかしこの規定値の一部ないしは全部を別の値でもって上書きできます:
15241523
15251524 use threads;
15261525 use Thread::Semaphore;
15271526
15281527 my $semaphore = Thread::Semaphore->new(5);
15291528 # Creates a semaphore with the counter set to five
15301529
15311530 my $thr1 = threads->create(\&sub1);
15321531 my $thr2 = threads->create(\&sub1);
15331532
15341533 sub sub1 {
15351534 $semaphore->down(5); # Decrements the counter by five
15361535 # Do stuff here
15371536 $semaphore->up(5); # Increment the counter by five
15381537 }
15391538
15401539 $thr1->detach();
15411540 $thr2->detach();
15421541
15431542=begin original
15441543
15451544If C<down()> attempts to decrement the counter below zero, it blocks until
15461545the counter is large enough. Note that while a semaphore can be created
15471546with a starting count of zero, any C<up()> or C<down()> always changes the
15481547counter by at least one, and so C<< $semaphore->down(0) >> is the same as
15491548C<< $semaphore->down(1) >>.
15501549
15511550=end original
15521551
15531552もしも C<down()> がカウンタを 0 より小さい値に下げようとするなら、
15541553カウンタが十分な大きさになるまでブロックします。
15551554セマフォはカウンタの値を 0 にして生成することができる一方、C<up()> や
1556C<down()> は常に、少なくとも 1 の変化をカウンタに対して行うことに
1555C<down()> は常に、少なくとも 1 の変化をカウンタに対して行うので、
1556C<< $semaphore->down(0) >> は C<< $semaphore->down(1) >> と同じであることに
15571557注意してください。
1558だから、C<< $semaphore->down(0) >> は C<< $semaphore->down(1) >> と同じです。
15591558
15601559=begin original
15611560
15621561The question, of course, is why would you do something like this? Why
15631562create a semaphore with a starting count that's not one, or why
15641563decrement or increment it by more than one? The answer is resource
15651564availability. Many resources that you want to manage access for can be
15661565safely used by more than one thread at once.
15671566
15681567=end original
15691568
15701569もちろん、問題はどうしてこんなことをするのかということです。
15711570なぜセマフォを 1 ではなくて、0 から始めるように生成するのでしょうか?
15721571あるいは、なぜ 1 より大きい値で増減を行うのでしょうか?
15731572その答えはリソースの利用可能性です。
15741573あなたがアクセス管理をしたいリソースの多くは、同時に一つを超える数の
15751574スレッドによって安全に利用されます。
15761575
15771576=begin original
15781577
15791578For example, let's take a GUI driven program. It has a semaphore that
15801579it uses to synchronize access to the display, so only one thread is
15811580ever drawing at once. Handy, but of course you don't want any thread
15821581to start drawing until things are properly set up. In this case, you
15831582can create a semaphore with a counter set to zero, and up it when
15841583things are ready for drawing.
15851584
15861585=end original
15871586
15881587例として GUI 駆動型のプログラムを取り上げてみましょう。
1589プログラムは、ディスプレイに同期アクセスするためにセマフォを持っています
1588プログラムは、ディスプレイに同期アクセスするためにセマフォを持っています;
15901589そうして一度にただ一つのスレッドだけが描画を行っています。
15911590簡単な話ですが、もちろん、ちゃんと準備ができるまでどのスレッドにも描画を
15921591始めてもらいたくはありません。
1593こんな場合に、カウンタを 0 にしてセマフォを生成するのです
1592こんな場合に、カウンタを 0 にしてセマフォを生成するのです; そして描画の
1594そして描画の準備ができたら、カウンタを増加させます。
1593準備ができたら、カウンタを増加させます。
15951594
15961595=begin original
15971596
15981597Semaphores with counters greater than one are also useful for
15991598establishing quotas. Say, for example, that you have a number of
16001599threads that can do I/O at once. You don't want all the threads
16011600reading or writing at once though, since that can potentially swamp
1602your I/O channels, or deplete your process' quota of filehandles. You
1601your I/O channels, or deplete your process's quota of filehandles. You
16031602can use a semaphore initialized to the number of concurrent I/O
16041603requests (or open files) that you want at any one time, and have your
16051604threads quietly block and unblock themselves.
16061605
16071606=end original
16081607
160916081 より大きいカウンタを持つセマフォはクォータの確立にも役立ちます。
16101609例えば、同時に I/O を使うスレッドがいくつもあるとします。
1611だが、全てのスレッドが同時に読み書きをするのは望みません
1610だが、全てのスレッドが同時に読み書きをするのは望みません;
16121611そんなことをしたら I/O チャンネルを圧迫するかもしれないし、プロセスに
16131612割り当てられたファイルハンドルを枯渇させてしまうかもしれないからです。
16141613あなたがいつでも必要とし、スレッドに暗黙にブロック・アンブロックを
16151614させたいだけの同時 I/O リクエスト数(あるいはオープンファイル数)で
16161615初期設定されたセマフォを利用すればよいです。
16171616
16181617=begin original
16191618
16201619Larger increments or decrements are handy in those cases where a
16211620thread needs to check out or return a number of resources at once.
16221621
16231622=end original
16241623
16251624あるスレッドが一度にたくさんのリソースを借りたり戻したりするような
16261625こういうケースでは、大きな数で増減を行うのが便利です。
16271626
16281627=head2 Waiting for a Condition
16291628
16301629(条件を待つ)
16311630
16321631=begin original
16331632
16341633The functions C<cond_wait()> and C<cond_signal()>
16351634can be used in conjunction with locks to notify
16361635co-operating threads that a resource has become available. They are
16371636very similar in use to the functions found in C<pthreads>. However
16381637for most purposes, queues are simpler to use and more intuitive. See
16391638L<threads::shared> for more details.
16401639
16411640=end original
16421641
16431642関数 C<cond_wait()> と C<cond_signal()> は、ロックが同時発生する時に、
16441643リソースが利用可能になった協調型スレッドに通知を行うために用います。
16451644これらは、C<pthreads> にある関数とよく似ています。
16461645しかしほとんどの目的において、キューの方がより単純で直感的です。
16471646更なる詳細は L<threads::shared> を参照してください。
16481647
16491648=head2 Giving up control
16501649
16511650(制御の明け渡し)
16521651
16531652=begin original
16541653
16551654There are times when you may find it useful to have a thread
16561655explicitly give up the CPU to another thread. You may be doing something
16571656processor-intensive and want to make sure that the user-interface thread
16581657gets called frequently. Regardless, there are times that you might want
16591658a thread to give up the processor.
16601659
16611660=end original
16621661
16631662あるスレッドが明示的に他のスレッドへと CPU を譲り渡せられたら便利だと
16641663思うことがあるでしょう。
16651664あなたはプロセッサ集約的なことをしようとしているかもしれませんし、
16661665ユーザーインターフェース担当のスレッドが呼び出されることを確認したいと
16671666思うかもしれません。
16681667とにかく、スレッドがプロセッサを明け渡せたら、ということがよくあります。
16691668
16701669=begin original
16711670
16721671Perl's threading package provides the C<yield()> function that does
16731672this. C<yield()> is pretty straightforward, and works like this:
16741673
16751674=end original
16761675
16771676Perl のスレッドパッケージはこれを実現する C<yield()> 関数を提供しています。
16781677C<yield()> はとても素朴で、このように動作します:
16791678
16801679 use threads;
16811680
16821681 sub loop {
16831682 my $thread = shift;
16841683 my $foo = 50;
16851684 while($foo--) { print("In thread $thread\n"); }
16861685 threads->yield();
16871686 $foo = 50;
16881687 while($foo--) { print("In thread $thread\n"); }
16891688 }
16901689
16911690 my $thr1 = threads->create(\&loop, 'first');
16921691 my $thr2 = threads->create(\&loop, 'second');
16931692 my $thr3 = threads->create(\&loop, 'third');
16941693
16951694=begin original
16961695
16971696It is important to remember that C<yield()> is only a hint to give up the CPU,
16981697it depends on your hardware, OS and threading libraries what actually happens.
16991698B<On many operating systems, yield() is a no-op.> Therefore it is important
17001699to note that one should not build the scheduling of the threads around
17011700C<yield()> calls. It might work on your platform but it won't work on another
17021701platform.
17031702
17041703=end original
17051704
1706C<yield()> は CPU を明け渡すためのヒントでしかありません
1705C<yield()> は CPU を明け渡すためのヒントでしかありません; 実際に何が
1707実際に何が起こるのかは、ハードウェアや OS、そしてスレッドライブラリに
1706起こるのかは、ハードウェアや OS、そしてスレッドライブラリに依存しています。
1708依存しています。
17091707B<多くのオペレーティングシステムにおいて、yield() は何も機能しません。>
17101708それゆえ、C<yield()> を呼んでスレッドのスケジューリングをたてるべきでは
17111709ないことに注意することが重要です。
17121710あなたのプラットフォームでは動作したとしても、別のプラットフォームでは
17131711動かないかもしれません。
17141712
17151713=head1 General Thread Utility Routines
17161714
17171715(一般的なスレッドユーティリティルーチン)
17181716
17191717=begin original
17201718
17211719We've covered the workhorse parts of Perl's threading package, and
17221720with these tools you should be well on your way to writing threaded
17231721code and packages. There are a few useful little pieces that didn't
17241722really fit in anyplace else.
17251723
17261724=end original
17271725
1728Perlのスレッドパッケージの働き部分をみてきました
1726Perlのスレッドパッケージの働き部分をみてきました; これらの道具を使い、
1729これらの道具を使い、あなたのやり方でスレッドコードとパッケージを
1727あなたのやり方でスレッドコードとパッケージを書いていくことができるはずです。
1730書いていくことができるはずです。
17311728他の場所では実際にはフィットしないけれども、便利な小物も少しはあります。
17321729
17331730=head2 What Thread Am I In?
17341731
17351732(私はどのスレッドにいる?)
17361733
17371734=begin original
17381735
17391736The C<threads-E<gt>self()> class method provides your program with a way to
17401737get an object representing the thread it's currently in. You can use this
17411738object in the same way as the ones returned from thread creation.
17421739
17431740=end original
17441741
17451742C<threads-E<gt>self()> クラスメソッドを使うと、現在のスレッドを表す
17461743オブジェクトを得ることができます。
17471744スレッドを生成するときに返ってくるオブジェクトと同じように、この
17481745オブジェクトを使うことができます。
17491746
17501747=head2 Thread IDs
17511748
17521749(スレッド ID)
17531750
17541751=begin original
17551752
17561753C<tid()> is a thread object method that returns the thread ID of the
17571754thread the object represents. Thread IDs are integers, with the main
17581755thread in a program being 0. Currently Perl assigns a unique TID to
17591756every thread ever created in your program, assigning the first thread
17601757to be created a TID of 1, and increasing the TID by 1 for each new
17611758thread that's created. When used as a class method, C<threads-E<gt>tid()>
17621759can be used by a thread to get its own TID.
17631760
17641761=end original
17651762
17661763C<tid()> はオブジェクトが表すスレッドの ID を返すメソッドです。
17671764スレッド ID は整数で、プログラム中のメインスレッドは 0 です。
17681765現在の Perl は、プログラム中で生成された全てのスレッドに一意な ID を
1769つけます
1766つけます; 最初に生成されたスレッドには 1 があてられ、新しいスレッドが
1770最初に生成さたスレッドには 1 があられ、新しスレッドが作られる度に
1767作らる度 ID は 1 ずつ増えていきます。
1771ID は 1 ずつ増えていきます。
17721768クラスメソッドとして使われると、C<threads-E<gt>tid()> はスレッドが自身の
17731769TID を得るために使われます。
17741770
17751771=head2 Are These Threads The Same?
17761772
17771773(このスレッドは同じものか?)
17781774
17791775=begin original
17801776
17811777The C<equal()> method takes two thread objects and returns true
17821778if the objects represent the same thread, and false if they don't.
17831779
17841780=end original
17851781
17861782C<equal()> メソッドは二つのスレッドオブジェクトを引数にとり、オブジェクトが
17871783同じスレッドを示していれば真を、そうでなければ偽を返します。
17881784
17891785=begin original
17901786
17911787Thread objects also have an overloaded C<==> comparison so that you can do
17921788comparison on them as you would with normal objects.
17931789
17941790=end original
17951791
17961792スレッドオブジェクトは比較演算子 C<==> をオーバーロードするので、普通の
17971793オブジェクトのようにそれらを比較することもできます。
17981794
17991795=head2 What Threads Are Running?
18001796
18011797(どのスレッドが実行されているのか?)
18021798
18031799=begin original
18041800
18051801C<threads-E<gt>list()> returns a list of thread objects, one for each thread
18061802that's currently running and not detached. Handy for a number of things,
18071803including cleaning up at the end of your program (from the main Perl thread,
18081804of course):
18091805
18101806=end original
18111807
1812C<threads-E<gt>list()> はスレッドオブジェクトのリストを返します
1808C<threads-E<gt>list()> はスレッドオブジェクトのリストを返します;
18131809それぞれは現在実行中で detach されていないスレッドです。
18141810プログラムの終わりに(もちろん Perl のメインスレッドから)
18151811クリーンナップするのも含めていろいろな点で便利です:
18161812
18171813 # Loop through all the threads
18181814 foreach my $thr (threads->list()) {
18191815 $thr->join();
18201816 }
18211817
18221818=begin original
18231819
18241820If some threads have not finished running when the main Perl thread
18251821ends, Perl will warn you about it and die, since it is impossible for Perl
18261822to clean up itself while other threads are running.
18271823
18281824=end original
18291825
18301826もしメインスレッドが終了する時に、あるスレッドが実行を終了していなかったら、
1831Perl は警告を発し、die します
1827Perl は警告を発し、die します; これは、他のスレッドが実行中の間は Perl が
1832これは、他のスレッドが実行中の間は Perl が自分自身をクリーンナップ
1828自分自身をクリーンナップできないためです。
1833できないためです。
18341829
18351830=begin original
18361831
18371832NOTE: The main Perl thread (thread 0) is in a I<detached> state, and so
18381833does not appear in the list returned by C<threads-E<gt>list()>.
18391834
18401835=end original
18411836
18421837注意: Perl のメインスレッド (スレッド 0) は I<detach された> 状態にあるので、
18431838C<threads-E<gt>list()> で返されるリストには現れません。
18441839
18451840=head1 A Complete Example
18461841
18471842(完全な例)
18481843
18491844=begin original
18501845
18511846Confused yet? It's time for an example program to show some of the
18521847things we've covered. This program finds prime numbers using threads.
18531848
18541849=end original
18551850
18561851まだ混乱していますか?
18571852では、サンプルプログラムを使ってこれまで見てきたことのいくつかを示す時です。
18581853このプログラムはスレッドを使って素数を見つけだします。
18591854
1860 1 #!/usr/bin/perl
1855 1 #!/usr/bin/perl
1861 2 # prime-pthread, courtesy of Tom Christiansen
1856 2 # prime-pthread, courtesy of Tom Christiansen
1862 3
1857 3
1863 4 use strict;
1858 4 use v5.36;
1864 5 use warnings;
1859 5
1865 6
1860 6 use threads;
1866 7 use threads;
1861 7 use Thread::Queue;
1867 8 use Thread::Queue;
1862 8
1868 9
1863 9 sub check_num ($upstream, $cur_prime) {
1869 10 sub check_num {
1864 10 my $kid;
1870 11 my ($upstream, $cur_prime) = @_;
1865 11 my $downstream = Thread::Queue->new();
1871 12 my $kid;
1866 12 while (my $num = $upstream->dequeue()) {
1872 13 my $downstream = Thread::Queue->new();
1867 13 next unless ($num % $cur_prime);
1873 14 while (my $num = $upstream->dequeue()) {
1868 14 if ($kid) {
1874 15 next unless ($num % $cur_prime);
1869 15 $downstream->enqueue($num);
1875 16 if ($kid) {
1870 16 } else {
1876 17 $downstream->enqueue($num);
1871 17 print("Found prime: $num\n");
1877 18 } else {
1872 18 $kid = threads->create(\&check_num, $downstream, $num);
1878 19 print("Found prime: $num\n");
1873 19 if (! $kid) {
1879 20 $kid = threads->create(\&check_num, $downstream, $num);
1874 20 warn("Sorry. Ran out of threads.\n");
1880 21 if (! $kid) {
1875 21 last;
1881 22 warn("Sorry. Ran out of threads.\n");
1876 22 }
1882 23 last;
1877 23 }
1883 24 }
1878 24 }
1884 25 }
1879 25 if ($kid) {
1885 26 }
1880 26 $downstream->enqueue(undef);
1886 27 if ($kid) {
1881 27 $kid->join();
1887 28 $downstream->enqueue(undef);
1882 28 }
1888 29 $kid->join();
1883 29 }
1889 30 }
1884 30
1890 31 }
1885 31 my $stream = Thread::Queue->new(3..1000, undef);
1891 32
1886 32 check_num($stream, 2);
1892 33 my $stream = Thread::Queue->new(3..1000, undef);
1893 34 check_num($stream, 2);
18941887
18951888=begin original
18961889
18971890This program uses the pipeline model to generate prime numbers. Each
18981891thread in the pipeline has an input queue that feeds numbers to be
18991892checked, a prime number that it's responsible for, and an output queue
19001893into which it funnels numbers that have failed the check. If the thread
19011894has a number that's failed its check and there's no child thread, then
19021895the thread must have found a new prime number. In that case, a new
19031896child thread is created for that prime and stuck on the end of the
19041897pipeline.
19051898
19061899=end original
19071900
19081901このプログラムは素数を発生させるためにパイプラインモデルを利用しています。
19091902パイプラインにおけるそれぞれのスレッドは、素数を見つけるために
19101903チェックされる数を渡す入力キューと、チェックに失敗した数をかき集めておく
19111904出力キューとを持ちます。
19121905チェックに失敗した数がスレッドにあり、かつ、子スレッドがない場合、その
19131906スレッドは新しい素数を見つけたことになります。
19141907この場合、新しい子スレッドはその素数のために生成され、パイプラインの後ろに
19151908くっつけられます。
19161909
19171910=begin original
19181911
19191912This probably sounds a bit more confusing than it really is, so let's
19201913go through this program piece by piece and see what it does. (For
19211914those of you who might be trying to remember exactly what a prime
19221915number is, it's a number that's only evenly divisible by itself and 1.)
19231916
19241917=end original
19251918
1926これは実際よりもわかりにくいかもしれません
1919これは実際よりもわかりにくいかもしれません; だからこのプログラムを部分部分に
1927だからこのプログラムを部分部分に分けて、なにをしているのかを見てみましょう。
1920分けて、なにをしているのかを見てみましょう。
19281921(素数とは正確には何だったかということを思い出そうされている方のためにいうと、
19291922自分自身と 1 でのみ割り切れる数のことです。)
19301923
19311924=begin original
19321925
19331926The bulk of the work is done by the C<check_num()> subroutine, which
19341927takes a reference to its input queue and a prime number that it's
1935responsible for. After pulling in the input queue and the prime that
1928responsible for. We create a new queue (line 11) and reserve a scalar
1936the subroutine is checking (line 11), we create a new queue (line 13)
1929for the thread that we're likely to create later (line 10).
1937and reserve a scalar for the thread that we're likely to create later
1938(line 12).
19391930
19401931=end original
19411932
1942作業の大半は C<check_num()> ルーチンによってなされます
1933作業の大半は C<check_num()> ルーチンによってなされます; このルーチンは
1943このルーチンは入力キューへのリファレンスとスレッドが受け持つ素数を
1934入力キューへのリファレンスとスレッドが受け持つ素数を引数にとります。
1944引数にとります
1935新しいキューを生成します(13 行目); そして、後で
1945[引数]力キューとサブルーチンがチェックす素数[のロー変数]に
1936生成するかもしれないスレッドを入変数を用意します(12 行目)。
1946入れた後(11 行目)、新しいキューを生成します(13 行目)。
1947そして、後で生成するかもしれないスレッドを入れるスカラ変数を
1948用意します(12 行目)。
19491937
19501938=begin original
19511939
1952The while loop from line 14 to line 26 grabs a scalar off the input
1940The while loop from line 12 to line 24 grabs a scalar off the input
19531941queue and checks against the prime this thread is responsible
1954for. Line 15 checks to see if there's a remainder when we divide the
1942for. Line 13 checks to see if there's a remainder when we divide the
19551943number to be checked by our prime. If there is one, the number
19561944must not be evenly divisible by our prime, so we need to either pass
1957it on to the next thread if we've created one (line 17) or create a
1945it on to the next thread if we've created one (line 15) or create a
19581946new thread if we haven't.
19591947
19601948=end original
19611949
196214 行目から 26 行目までの while ループで入力キューからスカラ値を
195012 行目から 24 行目までの while ループで入力キューからスカラ値を
19631951取り出し、このスレッドが受け持つ素数でチェックします。
196415 行目では、チェックされる数に対する除算を行い、余りがあるかどうかを
195213 行目では、チェックされる数に対する除算を行い、余りがあるかどうかを
19651953調べます。
19661954もしあれば、その数は素数では割れないということなので、
1967その数を、すでに生成してあるのであれば (17 行目) 次のスレッドに渡しますし、
1955その数を、すでに生成してあるのであれば (15 行目) 次のスレッドに渡しますし、
19681956そうでなければ新しいスレッドを作ります。
19691957
19701958=begin original
19711959
1972The new thread creation is line 20. We pass on to it a reference to
1960The new thread creation is line 18. We pass on to it a reference to
1973the queue we've created, and the prime number we've found. In lines 21
1961the queue we've created, and the prime number we've found. In lines 19
1974through 24, we check to make sure that our new thread got created, and
1962through 22, we check to make sure that our new thread got created, and
19751963if not, we stop checking any remaining numbers in the queue.
19761964
19771965=end original
19781966
197920 行目で新しいスレッドの生成を行っています。
196718 行目で新しいスレッドの生成を行っています。
19801968そのスレッドに、先に作ったキューへのリファレンスと発見された素数を渡します。
198121 行目から 24 行目で、新しいスレッドが作成されたことを確認して、
196919 行目から 22 行目で、新しいスレッドが作成されたことを確認して、
19821970もし作成されていないなら、キューの残りの番号に関するチェックを
19831971中止します。
19841972
19851973=begin original
19861974
19871975Finally, once the loop terminates (because we got a 0 or C<undef> in the
19881976queue, which serves as a note to terminate), we pass on the notice to our
1989child, and wait for it to exit if we've created a child (lines 27 and
1977child, and wait for it to exit if we've created a child (lines 25 and
199030).
197828).
19911979
19921980=end original
19931981
19941982最後に、(キューの中に 0 か C<undef> があるかして)ループが終了すると、
19951983子スレッドを作っていた場合には子スレッドに注意を促し[(undef を送る)]、
1996実行が終了するのを待ちます(27, 30 行目)。
1984実行が終了するのを待ちます(25, 28 行目)。
19971985
19981986=begin original
19991987
2000Meanwhile, back in the main thread, we first create a queue (line 33) and
1988Meanwhile, back in the main thread, we first create a queue (line 31) and
20011989queue up all the numbers from 3 to 1000 for checking, plus a termination
20021990notice. Then all we have to do to get the ball rolling is pass the queue
2003and the first prime to the C<check_num()> subroutine (line 34).
1991and the first prime to the C<check_num()> subroutine (line 32).
20041992
20051993=end original
20061994
2007一方、メインスレッドに戻ってみると、まずキューを生成し(33 行目)、
1995一方、メインスレッドに戻ってみると、まずキューを生成し(31 行目)、
20081996チェックするための 3 から 1000 までの全ての数と終端マークを
20091997キューに入れます。
20101998それからボールを転がすために必要なことは、キューと最初の素数を
2011C<check_num()> サブルーチンに渡すことです (line 34)。
1999C<check_num()> サブルーチンに渡すことです (32 行目)。
20122000
20132001=begin original
20142002
20152003That's how it works. It's pretty simple; as with many Perl programs,
20162004the explanation is much longer than the program.
20172005
20182006=end original
20192007
20202008以上が仕組みです。
20212009とても単純です; 多くのPerlプログラムにとってそうであるように、
20222010説明の方が当のプログラム以上にとても長くなります。
20232011
20242012=head1 Different implementations of threads
20252013
20262014(様々なスレッドの実装)
20272015
20282016=begin original
20292017
20302018Some background on thread implementations from the operating system
20312019viewpoint. There are three basic categories of threads: user-mode threads,
20322020kernel threads, and multiprocessor kernel threads.
20332021
20342022=end original
20352023
20362024オペレーティングシステムの観点からみた、スレッド実装についての背景です。
20372025スレッドには三つの基本的なカテゴリーがあります: ユーザーモードスレッド、
20382026カーネルスレッド、マルチプロセッサカーネルスレッドです。
20392027
20402028=begin original
20412029
20422030User-mode threads are threads that live entirely within a program and
20432031its libraries. In this model, the OS knows nothing about threads. As
20442032far as it's concerned, your process is just a process.
20452033
20462034=end original
20472035
20482036ユーザーモードスレッドとは、完全にプログラムとライブラリの中に存在する
20492037スレッドです。
20502038このモデルにおいては、OS はスレッドについて何も関知しません。
20512039OS からしてみる限り、あなたのプロセスはただのひとつのプロセスです。
20522040
20532041=begin original
20542042
20552043This is the easiest way to implement threads, and the way most OSes
20562044start. The big disadvantage is that, since the OS knows nothing about
20572045threads, if one thread blocks they all do. Typical blocking activities
20582046include most system calls, most I/O, and things like C<sleep()>.
20592047
20602048=end original
20612049
20622050これは最も簡単なスレッドの実装であり、ほとんどの OS が最初にとった方法です。
20632051この方法の大きな欠点は、OS がスレッドに関知していないために、
20642052もしも一つのスレッドがブロックをしたら、全てのスレッドがブロックしてしまう
20652053ということです。
20662054典型的なブロック行為には、ほとんどのシステムコール、ほとんどの
20672055I/O、そして C<sleep()> のようなものが含まれます。
20682056
20692057=begin original
20702058
20712059Kernel threads are the next step in thread evolution. The OS knows
20722060about kernel threads, and makes allowances for them. The main
20732061difference between a kernel thread and a user-mode thread is
20742062blocking. With kernel threads, things that block a single thread don't
20752063block other threads. This is not the case with user-mode threads,
20762064where the kernel blocks at the process level and not the thread level.
20772065
20782066=end original
20792067
20802068カーネルスレッドは進化の第二段階です。
20812069OS はカーネルスレッドについて知っていて、その許可を出します。
20822070カーネルスレッドとユーザーモードスレッドの主要な違いは、
20832071ブロッキングについてです。
20842072カーネルスレッドでは、一つのスレッドをブロックした事で他のスレッドまで
20852073ブロックすることはありません。
2086これはユーザーモードスレッドにおいては成り立ちません
2074これはユーザーモードスレッドにおいては成り立ちません; ユーザーモードでは、
2087ユーザーモードでは、カーネルがブロックするのはプロセスレベルであって、
2075カーネルがブロックするのはプロセスレベルであって、スレッドレベルでは
2088スレッドレベルではないからです。
2076ないからです。
20892077
20902078=begin original
20912079
20922080This is a big step forward, and can give a threaded program quite a
20932081performance boost over non-threaded programs. Threads that block
20942082performing I/O, for example, won't block threads that are doing other
20952083things. Each process still has only one thread running at once,
20962084though, regardless of how many CPUs a system might have.
20972085
20982086=end original
20992087
21002088これは大きな前進であり、非スレッドプログラムに対し、スレッドプログラムが
21012089大きなパフォーマンスの向上を得ることを可能にしています。
21022090例えば、I/O の実行をブロックするスレッドは、他のことを行うスレッドを
21032091ブロックしないでしょう。
21042092しかし、システムがいくつ CPU を備えているかに関係なく、それぞれのプロセスは
21052093いまだに一度に一つのスレッドしか走らせません。
21062094
21072095=begin original
21082096
21092097Since kernel threading can interrupt a thread at any time, they will
21102098uncover some of the implicit locking assumptions you may make in your
2111program. For example, something as simple as C<$a = $a + 2> can behave
2099program. For example, something as simple as C<$x = $x + 2> can behave
2112unpredictably with kernel threads if C<$a> is visible to other
2100unpredictably with kernel threads if C<$x> is visible to other
2113threads, as another thread may have changed C<$a> between the time it
2101threads, as another thread may have changed C<$x> between the time it
21142102was fetched on the right hand side and the time the new value is
21152103stored.
21162104
21172105=end original
21182106
21192107カーネルのスレッド制御がいつでも割り込めるので、あなたがプログラム中に
21202108つくった暗黙のロックの前提が白日の下にさらけ出してしまうでしょう。
2121例えば、C<$a = $a + 2>のような単純なものでも、C<$a> が他のスレッドから
2109例えば、C<$x = $x + 2>のような単純なものでも、C<$x> が他のスレッドから
21222110見えるならば、右辺の値を取り出す時間と新しい値を格納する時間の間に、他の
2123スレッドが C<$a> を変えてしまって、あなたの予期しない振る舞いをする
2111スレッドが C<$x> を変えてしまって、あなたの予期しない振る舞いをする
21242112可能性があります。
21252113
21262114=begin original
21272115
21282116Multiprocessor kernel threads are the final step in thread
21292117support. With multiprocessor kernel threads on a machine with multiple
21302118CPUs, the OS may schedule two or more threads to run simultaneously on
21312119different CPUs.
21322120
21332121=end original
21342122
21352123マルチプロセッサカーネルスレッドは、スレッドのサポートにおける最終段階です。
21362124一台のマシンが複数の CPU を持っているマルチプロセッサカーネルスレッドでは、
21372125OS は別々の CPU 上で同時に一つ以上のスレッドを走らせるようにスケジュール
21382126管理をします。
21392127
21402128=begin original
21412129
21422130This can give a serious performance boost to your threaded program,
21432131since more than one thread will be executing at the same time. As a
21442132tradeoff, though, any of those nagging synchronization issues that
21452133might not have shown with basic kernel threads will appear with a
21462134vengeance.
21472135
21482136=end original
21492137
21502138一つ以上のスレッドが同時に実行するので、これによりスレッドプログラムは
21512139飛躍的なパフォーマンスの向上を得ることができます。
21522140しかし、引き換えに、基本的なカーネルスレッドでは現れなかったであろう
21532141イライラするような同期性の問題が一気に姿を現します。
21542142
21552143=begin original
21562144
21572145In addition to the different levels of OS involvement in threads,
21582146different OSes (and different thread implementations for a particular
21592147OS) allocate CPU cycles to threads in different ways.
21602148
21612149=end original
21622150
21632151スレッドを備える OS の違いというレベルに加えて、それぞれの OS は(そして
21642152それぞれのスレッド実装は)それぞれの方法でもって CPU サイクルをスレッドに
21652153割り当てます。
21662154
21672155=begin original
21682156
21692157Cooperative multitasking systems have running threads give up control
21702158if one of two things happen. If a thread calls a yield function, it
21712159gives up control. It also gives up control if the thread does
21722160something that would cause it to block, such as perform I/O. In a
21732161cooperative multitasking implementation, one thread can starve all the
21742162others for CPU time if it so chooses.
21752163
21762164=end original
21772165
21782166次の二つのうちの一つが起こる場合、協調的マルチタスクシステムは実行中の
21792167スレッドに制御を明け渡させます。
21802168あるスレッドがyield関数を呼び出すと、制御を明け渡します。
21812169また、スレッドがI/Oの実行などのブロックを引き起こすような何かを行う場合も、
21822170制御を明け渡します。
21832171協調的マルチタスクシステムの実装においては、そのように選択するならば、
21842172一つのスレッドが他の全てのスレッドの CPU 時間を食い尽くすことができます。
21852173
21862174=begin original
21872175
21882176Preemptive multitasking systems interrupt threads at regular intervals
21892177while the system decides which thread should run next. In a preemptive
21902178multitasking system, one thread usually won't monopolize the CPU.
21912179
21922180=end original
21932181
21942182プリエンティブなマルチタスクシステムは、次にどのスレッドを実行するか
21952183決めながら、一定の間隔でスレッドに割り込みを入れます。
21962184プリエンティブなマルチタスクシステムにおいて、通常一つのスレッドが CPU を
21972185独占することはありません。
21982186
21992187=begin original
22002188
22012189On some systems, there can be cooperative and preemptive threads
22022190running simultaneously. (Threads running with realtime priorities
22032191often behave cooperatively, for example, while threads running at
22042192normal priorities behave preemptively.)
22052193
22062194=end original
22072195
22082196いくつかのシステムでは、協調的スレッドとプリエンティブなスレッドを同時に
2209実行することができます(例えば、通常のプライオリティを持ったスレッドが
2197実行することができます
2210プリエンディブに振舞うのに対してリアルタイムのプライオリティを持った
2198(例えば通常のプライオリティを持ったスレッドがプリエンディブに振舞うのに
2211スレッドはしばしば協調的に振舞います)。
2199対して、リアルタイムのプライオリティを持ったスレッドはしばしば協調的に
2200振舞います。)
22122201
22132202=begin original
22142203
22152204Most modern operating systems support preemptive multitasking nowadays.
22162205
22172206=end original
22182207
22192208今では、ほとんどの近代的なOSでプリエンティブなマルチタスクを
22202209サポートしています。
22212210
22222211=head1 Performance considerations
22232212
22242213(パフォーマンスの考慮)
22252214
22262215=begin original
22272216
22282217The main thing to bear in mind when comparing Perl's I<ithreads> to other threading
22292218models is the fact that for each new thread created, a complete copy of
22302219all the variables and data of the parent thread has to be taken. Thus,
22312220thread creation can be quite expensive, both in terms of memory usage and
22322221time spent in creation. The ideal way to reduce these costs is to have a
22332222relatively short number of long-lived threads, all created fairly early
2234on -- before the base thread has accumulated too much data. Of course, this
2223on (before the base thread has accumulated too much data). Of course, this
22352224may not always be possible, so compromises have to be made. However, after
22362225a thread has been created, its performance and extra memory usage should
22372226be little different than ordinary code.
22382227
22392228=end original
22402229
22412230Perl の I<iスレッド> と他のスレッドモデルを比較する際に忘れてならないのが、
22422231新しいスレッドはみな、親スレッドの変数とデータを全て完全にコピーして
22432232引き渡されるという事実です。
22442233そのため、メモリ使用量と実行時間の両方の点で、スレッドの生成は非常に
22452234高くつきます。
22462235このコストを減らす理想的な方法は、長生きなスレッドを比較的少なめに
2247持つことです
2236持つことです; このスレッドは全て (ベースとなるスレッドが非常に多くのデータを
2248このスレッドは全て、ベースとなるスレッドが非常に多くのデータを蓄積する前に
2237蓄積する前に) 適切に早い段階で生成されます。
2249適切に早い段階で生成されます。
22502238もちろん、これはいつも可能というわけではないでしょうから、妥協も必要です。
22512239しかし、スレッドが生成された後は、そのパフォーマンスと追加のメモリ使用量は、
22522240普通のコードのそれとほとんど違いはありません。
22532241
22542242=begin original
22552243
22562244Also note that under the current implementation, shared variables
22572245use a little more memory and are a little slower than ordinary variables.
22582246
22592247=end original
22602248
22612249また、現在の実装下では、共有変数は通常の変数に比べて少し余計にメモリを
22622250使用し、スピードも少し遅いことにも注意してください。
22632251
22642252=head1 Process-scope Changes
22652253
22662254(プロセススコープの変更)
22672255
22682256=begin original
22692257
22702258Note that while threads themselves are separate execution threads and
22712259Perl data is thread-private unless explicitly shared, the threads can
22722260affect process-scope state, affecting all the threads.
22732261
22742262=end original
22752263
22762264スレッドそれ自身は別々に実行され、Perl のデータは明示的に共有化しない限りは
22772265スレッド内でプライベートなものです;
22782266その一方、スレッドは全てのスレッドに影響を与えながら、プロセススコープの
22792267状態に影響を与えてしまうことに注意してください。
22802268
22812269=begin original
22822270
22832271The most common example of this is changing the current working
22842272directory using C<chdir()>. One thread calls C<chdir()>, and the working
22852273directory of all the threads changes.
22862274
22872275=end original
22882276
22892277この最も一般的な例は C<chdir()> を使ったときに現在作業中のディレクトリが
22902278変更されてしまうことです。
22912279一つのスレッドが C<chdir()> を呼ぶと、全てのスレッドの作業ディレクトリが
22922280変更されます。
22932281
22942282=begin original
22952283
22962284Even more drastic example of a process-scope change is C<chroot()>:
22972285the root directory of all the threads changes, and no thread can
22982286undo it (as opposed to C<chdir()>).
22992287
23002288=end original
23012289
2302さらに劇的なプロセススコープの変更例は C<chroot()> です
2290さらに劇的なプロセススコープの変更例は C<chroot()> です: 全部のスレッドの
2303全部のスレッドのルートディレクトリが変更されます
2291ルートディレクトリが変更されます; スレッドはそれを元に戻すことはできません
2304スレッドはそれを元に戻すことはできません(C<chdir()> の場合は可能です)。
2292(C<chdir()> の場合は可能です)。
23052293
23062294=begin original
23072295
23082296Further examples of process-scope changes include C<umask()> and
23092297changing uids and gids.
23102298
23112299=end original
23122300
23132301さらなるプロセススコープ変化の例は、C<umask()> および uid や gid の変更です。
23142302
23152303=begin original
23162304
23172305Thinking of mixing C<fork()> and threads? Please lie down and wait
23182306until the feeling passes. Be aware that the semantics of C<fork()> vary
2319between platforms. For example, some UNIX systems copy all the current
2307between platforms. For example, some Unix systems copy all the current
23202308threads into the child process, while others only copy the thread that
23212309called C<fork()>. You have been warned!
23222310
23232311=end original
23242312
23252313C<fork()> とスレッドを混在させたらどうなるかって?
23262314そんな気分が失せるまで、横になって休んでいてください。
23272315C<fork()> の動作はプラットフォームによって異なることに注意してください。
2328例えば、UNIX システムには現状の全てのスレッドを子プロセスに
2316例えば、Unix システムには現状の全てのスレッドを子プロセスに
23292317コピーするものもありますが、C<fork()> を呼び出したスレッドのみを
23302318コピーするものもあります。
23312319あなたは警告されました!
23322320
23332321=begin original
23342322
23352323Similarly, mixing signals and threads may be problematic.
23362324Implementations are platform-dependent, and even the POSIX
23372325semantics may not be what you expect (and Perl doesn't even
23382326give you the full POSIX API). For example, there is no way to
23392327guarantee that a signal sent to a multi-threaded Perl application
23402328will get intercepted by any particular thread. (However, a recently
23412329added feature does provide the capability to send signals between
2342threads. See L<threads/"THREAD SIGNALLING> for more details.)
2330threads. See L<threads/THREAD SIGNALLING> for more details.)
23432331
23442332=end original
23452333
23462334同じように、シグナルとスレッドを混ぜるのもするべきではありあません。
23472335実装はプラットフォーム依存だし、POSIX のセマンティクスでさえ、あなたの
23482336期待通りにはならないかもしれません
23492337(そして Perl はフルセットの POSIX API を提供することさえできません)。
23502338例えば、マルチスレッド Perl アプリケーションに送られたシグナルが、
23512339特定のスレッドによって受信されることを保証する方法はありません。
23522340(しかし、最近追加された機能はスレッド間でシグナルを送る能力を提供します。
2353更なる詳細については L<threads/"THREAD SIGNALLING> を参照してください。)
2341更なる詳細については L<threads/THREAD SIGNALLING> を参照してください。)
23542342
23552343=head1 Thread-Safety of System Libraries
23562344
23572345(システムライブラリにおけるスレッドの安全性)
23582346
2359=begin original
23602347
2361Whether various library calls are thread-safe is outside the control
2362of Perl. Calls often suffering from not being thread-safe include:
2363C<localtime()>, C<gmtime()>, functions fetching user, group and
2364network information (such as C<getgrent()>, C<gethostent()>,
2365C<getnetent()> and so on), C<readdir()>,
2366C<rand()>, and C<srand()> -- in general, calls that depend on some global
2367external state.
2368
2369=end original
2370
2371様々なライブラリの関数呼び出しがスレッドにとって安全かどうかということは、
2372Perlのコントロールの埒外です。
2373しばしばスレッドセーフではないものに
2374よって問題の生じる呼び出しには以下のようなものです:
2375C<localtime()>, C<gmtime()>,
2376(C<getgrent()>, C<gethostent()>, C<getnetent()> などのような)ユーザー、
2377グループ、ネットワークの情報を取り出す関数、C<readdir()>,
2378C<rand()>, C<srand()> -- 一般的に言って、グローバルな外部状況に依存する
2379呼び出しが含まれます。
2380
23812348=begin original
23822349
2383If the system Perl is compiled in has thread-safe variants of such
2350Whether C library calls are thread-safe is outside the control of Perl.
2384calls, they will be used. Beyond that, Perl is at the mercy of
2351Undefined behavior will happen if unsafe ones are used during
2385the thread-safety or -unsafety of the calls. Please consult your
2352multi-thread operation. See
2386C library call documentation.
2353L<perlclib/Dealing with embedded perls and threads>.
23872354
23882355=end original
23892356
2390Perl がコンパルされたシステムが、そういった呼び出しスレッドセーフ
2357C ブラリの呼び出しスレッドセーフかどうかということは、
2391バージョンを持っているなら、そちらが使われます。
2358Perl の制御の範囲外です。
2392それを超えると、Perl は呼び出しがスレッドセーフかどうかのすがままに
2359マルチスレッド操作中にスレッドセーフいものを使うと、
2393ります。
2360未定義の振る舞いが起こります。
2394C ライブラリのドキュメントよく吟味してください。
2361L<perlclib/Dealing with embedded perls and threads> 参照してください。
23952362
2396=begin original
2397
2398On some platforms the thread-safe library interfaces may fail if the
2399result buffer is too small (for example the user group databases may
2400be rather large, and the reentrant interfaces may have to carry around
2401a full snapshot of those databases). Perl will start with a small
2402buffer, but keep retrying and growing the result buffer
2403until the result fits. If this limitless growing sounds bad for
2404security or memory consumption reasons you can recompile Perl with
2405C<PERL_REENTRANT_MAXSIZE> defined to the maximum number of bytes you will
2406allow.
2407
2408=end original
2409
2410いくつかのプラットフォームでは、結果バッファが小さすぎる場合に
2411スレッドセーフなライブラリのインターフェースが失敗を起こすかもしれません
2412(例えば、ユーザーグループのデータベースがかなり大きく、リエントラントな
2413インターフェースがこれらのデータベースの完全なスナップショットを
2414もたらさなければならないような場合)。
2415Perl は小さなバッファでスタートします。
2416しかし結果が適合するまで結果バッファの確保を再試行し、大きくしようとします。
2417この無制限な成長がセキュリティやメモリ消費の理由から好ましくないもので
2418あるなら、C<PERL_REENTRANT_MAXSIZE> であなたの許す最大バイト数を定義して
2419Perl を再コンパイルできます。
2420
24212363=head1 Conclusion
24222364
24232365(おわりに)
24242366
24252367=begin original
24262368
24272369A complete thread tutorial could fill a book (and has, many times),
24282370but with what we've covered in this introduction, you should be well
24292371on your way to becoming a threaded Perl expert.
24302372
24312373=end original
24322374
2433完全なスレッドのチュートリアルをつくると一冊の本になってしまいます
2375完全なスレッドのチュートリアルをつくると一冊の本になってしまいます; しかし
2434しかしこの導入でカバーしてきたことを使って、あなたなりの方法で
2376この導入でカバーしてきたことを使って、あなたなりの方法でスレッド Perl の
2435スレッド Perl のエキスパートになっていってください。
2377エキスパートになっていってください。
24362378
24372379=head1 SEE ALSO
24382380
24392381Annotated POD for L<threads>:
2440L<http://annocpan.org/?mode=search&field=Module&name=threads>
2382L<https://web.archive.org/web/20171028020148/http://annocpan.org/?mode=search&field=Module&name=threads>
24412383
2442Lastest version of L<threads> on CPAN:
2384Latest version of L<threads> on CPAN:
2443L<http://search.cpan.org/search?module=threads>
2385L<https://metacpan.org/pod/threads>
24442386
24452387Annotated POD for L<threads::shared>:
2446L<http://annocpan.org/?mode=search&field=Module&name=threads%3A%3Ashared>
2388L<https://web.archive.org/web/20171028020148/http://annocpan.org/?mode=search&field=Module&name=threads%3A%3Ashared>
24472389
2448Lastest version of L<threads::shared> on CPAN:
2390Latest version of L<threads::shared> on CPAN:
2449L<http://search.cpan.org/search?module=threads%3A%3Ashared>
2391L<https://metacpan.org/pod/threads::shared>
24502392
24512393Perl threads mailing list:
2452L<http://lists.cpan.org/showlist.cgi?name=iThreads>
2394L<https://lists.perl.org/list/ithreads.html>
24532395
24542396=head1 Bibliography
24552397
24562398(参考文献)
24572399
24582400=begin original
24592401
2460Here's a short bibliography courtesy of Jurgen Christoffel:
2402Here's a short bibliography courtesy of Jürgen Christoffel:
24612403
24622404=end original
24632405
2464Jurgen Christoffel の提供による簡潔な参考文献集
2406Jürgen Christoffel の提供による簡潔な参考文献集:
24652407
24662408=head2 Introductory Texts
24672409
24682410(導入テキスト)
24692411
24702412Birrell, Andrew D. An Introduction to Programming with
24712413Threads. Digital Equipment Corporation, 1989, DEC-SRC Research Report
24722414#35 online as
2473http://gatekeeper.dec.com/pub/DEC/SRC/research-reports/abstracts/src-rr-035.html
2415L<https://www.hpl.hp.com/techreports/Compaq-DEC/SRC-RR-35.pdf>
24742416(highly recommended)
24752417
24762418Robbins, Kay. A., and Steven Robbins. Practical Unix Programming: A
24772419Guide to Concurrency, Communication, and
24782420Multithreading. Prentice-Hall, 1996.
24792421
24802422Lewis, Bill, and Daniel J. Berg. Multithreaded Programming with
24812423Pthreads. Prentice Hall, 1997, ISBN 0-13-443698-9 (a well-written
24822424introduction to threads).
24832425
24842426Nelson, Greg (editor). Systems Programming with Modula-3. Prentice
24852427Hall, 1991, ISBN 0-13-590464-1.
24862428
24872429Nichols, Bradford, Dick Buttlar, and Jacqueline Proulx Farrell.
24882430Pthreads Programming. O'Reilly & Associates, 1996, ISBN 156592-115-1
24892431(covers POSIX threads).
24902432
24912433=head2 OS-Related References
24922434
24932435(OS関連のリファレンス)
24942436
24952437Boykin, Joseph, David Kirschen, Alan Langerman, and Susan
24962438LoVerso. Programming under Mach. Addison-Wesley, 1994, ISBN
249724390-201-52739-1.
24982440
24992441Tanenbaum, Andrew S. Distributed Operating Systems. Prentice Hall,
250024421995, ISBN 0-13-219908-4 (great textbook).
25012443
25022444Silberschatz, Abraham, and Peter B. Galvin. Operating System Concepts,
250324454th ed. Addison-Wesley, 1995, ISBN 0-201-59292-4
25042446
25052447=head2 Other References
25062448
25072449(その他のリファレンス)
25082450
25092451Arnold, Ken and James Gosling. The Java Programming Language, 2nd
25102452ed. Addison-Wesley, 1998, ISBN 0-201-31006-6.
25112453
25122454comp.programming.threads FAQ,
25132455L<http://www.serpentine.com/~bos/threads-faq/>
25142456
25152457Le Sergent, T. and B. Berthomieu. "Incremental MultiThreaded Garbage
25162458Collection on Virtually Shared Memory Architectures" in Memory
25172459Management: Proc. of the International Workshop IWMM 92, St. Malo,
25182460France, September 1992, Yves Bekkers and Jacques Cohen, eds. Springer,
251924611992, ISBN 3540-55940-X (real-life thread applications).
25202462
25212463Artur Bergman, "Where Wizards Fear To Tread", June 11, 2002,
25222464L<http://www.perl.com/pub/a/2002/06/11/threads.html>
25232465
25242466=head1 Acknowledgements
25252467
25262468(謝辞)
25272469
2470=begin original
2471
25282472Thanks (in no particular order) to Chaim Frenkel, Steve Fink, Gurusamy
2529Sarathy, Ilya Zakharevich, Benjamin Sugars, Jurgen Christoffel, Joshua
2473Sarathy, Ilya Zakharevich, Benjamin Sugars, Jürgen Christoffel, Joshua
25302474Pritikin, and Alan Burlison, for their help in reality-checking and
25312475polishing this article. Big thanks to Tom Christiansen for his rewrite
25322476of the prime number generator.
25332477
2478=end original
2479
2480現実性のチェックとこの文章の磨き上げを助けてくれた以下の人々に
2481感謝します (順不同) Chaim Frenkel, Steve Fink, Gurusamy
2482Sarathy, Ilya Zakharevich, Benjamin Sugars, Jürgen Christoffel, Joshua
2483Pritikin, and Alan Burlison。
2484素数生成器を書き直してくれた Tom Christiansen にとても感謝します。
2485
25342486=head1 AUTHOR
25352487
25362488(著者)
25372489
2538Dan Sugalski E<lt>dan@sidhe.org<gt>
2490Dan Sugalski E<lt>dan@sidhe.orgE<gt>
25392491
25402492=begin original
25412493
25422494Slightly modified by Arthur Bergman to fit the new thread model/module.
25432495
25442496=end original
25452497
25462498新しいスレッドモデル・モジュールに対応するように Arthur Bergman によって
25472499若干の修正がなされました。
25482500
25492501=begin original
25502502
2551Reworked slightly by Jorg Walter E<lt>jwalt@cpan.org<gt> to be more concise
2503Reworked slightly by Jörg Walter E<lt>jwalt@cpan.orgE<gt> to be more concise
25522504about thread-safety of Perl code.
25532505
25542506=end original
25552507
25562508Perl コードのスレッドセーフティについてより簡明になるよう
2557Jorg Walter E<lt>jwalt@cpan.org<gt> によって改訂されました。
2509Jörg Walter E<lt>jwalt@cpan.orgE<gt> によって改訂されました。
25582510
25592511=begin original
25602512
2561Rearranged slightly by Elizabeth Mattijsen E<lt>liz@dijkmat.nl<gt> to put
2513Rearranged slightly by Elizabeth Mattijsen E<lt>liz@dijkmat.nlE<gt> to put
25622514less emphasis on yield().
25632515
25642516=end original
25652517
2566Elizabeth Mattijsen E<lt>liz@dijkmat.nl<gt> によって、yield() を以前より
2518Elizabeth Mattijsen E<lt>liz@dijkmat.nlE<gt> によって、yield() を以前より
25672519強調しないよう若干アレンジされました。
25682520
25692521=head1 Copyrights
25702522
25712523(著作権)
25722524
25732525The original version of this article originally appeared in The Perl
25742526Journal #10, and is copyright 1998 The Perl Journal. It appears courtesy
25752527of Jon Orwant and The Perl Journal. This document may be distributed
25762528under the same terms as Perl itself.
25772529
2530=cut
2531
25782532=begin meta
25792533
25802534Translate: まかまか <makamaka@donzoko.net> (-5.8.1)
25812535Update: SHIRAKATA Kentaro <argrath@ub32.org> (5.10.0-)
25822536Status: completed
25832537
25842538=end meta
2585
2586=cut