threads-1.72 > threads
threads-1.72

名前

threads - Perl interpreter-based threads

threads - Perl のインタプリタベースのスレッド

VERSION

This document describes threads version 1.72

この文書は threads バージョン 1.72 を記述しています。

概要

    use threads ('yield',
                 'stack_size' => 64*4096,
                 'exit' => 'threads_only',
                 'stringify');

    sub start_thread {
        my @args = @_;
        print('Thread started: ', join(' ', @args), "\n");
    }
    my $thr = threads->create('start_thread', 'argument');
    $thr->join();

    threads->create(sub { print("I am a thread\n"); })->join();

    my $thr2 = async { foreach (@files) { ... } };
    $thr2->join();
    if (my $err = $thr2->error()) {
        warn("Thread error: $err\n");
    }

    # Invoke thread in list context (implicit) so it can return a list
    my ($thr) = threads->create(sub { return (qw/a b c/); });
    # or specify list context explicitly
    my $thr = threads->create({'context' => 'list'},
                              sub { return (qw/a b c/); });
    my @results = $thr->join();

    $thr->detach();

    # Get a thread's object
    $thr = threads->self();
    $thr = threads->object($tid);

    # Get a thread's ID
    $tid = threads->tid();
    $tid = $thr->tid();
    $tid = "$thr";

    # Give other threads a chance to run
    threads->yield();
    yield();

    # Lists of non-detached threads
    my @threads = threads->list();
    my $thread_count = threads->list();

    my @running = threads->list(threads::running);
    my @joinable = threads->list(threads::joinable);

    # Test thread objects
    if ($thr1 == $thr2) {
        ...
    }

    # Manage thread stack size
    $stack_size = threads->get_stack_size();
    $old_size = threads->set_stack_size(32*4096);

    # Create a thread with a specific context and stack size
    my $thr = threads->create({ 'context'    => 'list',
                                'stack_size' => 32*4096,
                                'exit'       => 'thread_only' },
                              \&foo);

    # Get thread's context
    my $wantarray = $thr->wantarray();

    # Check thread's state
    if ($thr->is_running()) {
        sleep(1);
    }
    if ($thr->is_joinable()) {
        $thr->join();
    }

    # Send a signal to a thread
    $thr->kill('SIGUSR1');

    # Exit a thread
    threads->exit();

説明

Perl 5.6 introduced something called interpreter threads. Interpreter threads are different from 5005threads (the thread model of Perl 5.005) by creating a new Perl interpreter per thread, and not sharing any data or state between threads by default.

Perl 5.6 はインタプリタスレッドと呼ばれるものを導入しました。 インタプリタスレッドは、スレッド毎に新たに Perl インタプリタを 生成することによって、また、デフォルトではいかなるデータや状態も スレッド間で共有しないことによって、5005スレッド (Perl 5.005 におけるスレッドモデル)とは区別されます。

Prior to Perl 5.8, this has only been available to people embedding Perl, and for emulating fork() on Windows.

Perl 5.8 より前では、これは Perl を組み込むする人々にとってのみ、 そして Windows で fork() をエミュレートするためにのみ利用可能でした。

The threads API is loosely based on the old Thread.pm API. It is very important to note that variables are not shared between threads, all variables are by default thread local. To use shared variables one must also use threads::shared:

threads API は、古い Thread.pm API におおまかに基づいています。 変数はスレッド間で共有されず、全ての変数はデフォルトで スレッドローカルなものであることに注意しておくことが非常に重要です。 共有変数を利用するには、threads::shared を使わなければなりません。

    use threads;
    use threads::shared;

It is also important to note that you must enable threads by doing use threads as early as possible in the script itself, and that it is not possible to enable threading inside an eval "", do, require, or use. In particular, if you are intending to share variables with threads::shared, you must use threads before you use threads::shared. (threads will emit a warning if you do it the other way around.)

また、スクリプト内ではできるだけ早いうちに use threads して スレッドを利用可能にしておくべきだし、 eval "", do, require, use の内部では スレッド操作ができないことに注意してください。 特に threads::shared を使って変数を共有しようとするならば、 use threads::shared の前に use threads しなければなりません。 (逆にしてしまうと threads は警告を発します。)

$thr = threads->create(FUNCTION, ARGS)

This will create a new thread that will begin execution with the specified entry point function, and give it the ARGS list as parameters. It will return the corresponding threads object, or undef if thread creation failed.

これは指定されたエントリポイント関数の実行を開始し、引数として ARGS リストが与えられる新しいスレッドを作ります。 対応するスレッドオブジェクトか、スレッド作成に失敗した場合は undef を返します。

FUNCTION may either be the name of a function, an anonymous subroutine, or a code ref.

FUNCTION は関数名、無名サブルーチン、コードリファレンスのいずれかです。

    my $thr = threads->create('func_name', ...);
        # or
    my $thr = threads->create(sub { ... }, ...);
        # or
    my $thr = threads->create(\&func, ...);

The ->new() method is an alias for ->create().

->new() メソッドは ->create() のエイリアスです。

$thr->join()

This will wait for the corresponding thread to complete its execution. When the thread finishes, ->join() will return the return value(s) of the entry point function.

対応するスレッドが実行を終了するのを待ちます。 そのスレッドが終了した時、->join() は エントリポイント関数の戻り値を返します。

The context (void, scalar or list) for the return value(s) for ->join() is determined at the time of thread creation.

->join() のコンテキスト (無効、スカラ、リストのいずれか) は、 スレッド生成時に決定されます。

    # Create thread in list context (implicit)
    my ($thr1) = threads->create(sub {
                                    my @results = qw(a b c);
                                    return (@results);
                                 });
    #   or (explicit)
    my $thr1 = threads->create({'context' => 'list'},
                               sub {
                                    my @results = qw(a b c);
                                    return (@results);
                               });
    # Retrieve list results from thread
    my @res1 = $thr1->join();

    # Create thread in scalar context (implicit)
    my $thr2 = threads->create(sub {
                                    my $result = 42;
                                    return ($result);
                                 });
    # Retrieve scalar result from thread
    my $res2 = $thr2->join();

    # Create a thread in void context (explicit)
    my $thr3 = threads->create({'void' => 1},
                               sub { print("Hello, world\n"); });
    # Join the thread in void context (i.e., no return value)
    $thr3->join();

See "THREAD CONTEXT" for more details.

さらなる詳細については "THREAD CONTEXT" を参照してください。

If the program exits without all threads having either been joined or detached, then a warning will be issued.

全てのスレッドが join されるか detach される前にプログラムが終了した場合、 警告が発生します。

Calling ->join() or ->detach() on an already joined thread will cause an error to be thrown.

既に join しているスレッドに対して ->join()->detach() を 行うと、エラーが発生します。

$thr->detach()

Makes the thread unjoinable, and causes any eventual return value to be discarded. When the program exits, any detached threads that are still running are silently terminated.

スレッドを join 不可能にし、最終的な返り値を捨てるようにします。 プログラムが終了するとき、まだ実行中の detach されたスレッドは暗黙に 終了します。

If the program exits without all threads having either been joined or detached, then a warning will be issued.

全てのスレッドが join されるか detach される前にプログラムが終了した場合、 警告が発生します。

Calling ->join() or ->detach() on an already detached thread will cause an error to be thrown.

既に detach されたスレッドに ->join()->detach() を 呼び出すと、エラーが発生します。

threads->detach()

Class method that allows a thread to detach itself.

スレッドが自分自身を detach するためのクラスメソッドです。

threads->self()

Class method that allows a thread to obtain its own threads object.

スレッドが自身の threads オブジェクトを取得するためのクラスメソッドです。

$thr->tid()

Returns the ID of the thread. Thread IDs are unique integers with the main thread in a program being 0, and incrementing by 1 for every thread created.

スレッドの ID を返します。 スレッド ID はユニークな整数であり、プログラムの始まりとなる メインスレッドの値は 0 で、 新しいスレッドが生成されるたびに値を 1 増やしていきます。

threads->tid()

Class method that allows a thread to obtain its own ID.

スレッドが自身の ID を得るためのクラスメソッドです。

"$thr"

If you add the stringify import option to your use threads declaration, then using a threads object in a string or a string context (e.g., as a hash key) will cause its ID to be used as the value:

use threads 宣言に stringify インポートオプションを追加すると、 文字列や文字列コンテキスト (例えばハッシュのキーとして) で スレッドオブジェクトを使おうとすると、その ID が値として使われます:

    use threads qw(stringify);

    my $thr = threads->create(...);
    print("Thread $thr started...\n");  # Prints out: Thread 1 started...
threads->object($tid)

This will return the threads object for the active thread associated with the specified thread ID. Returns undef if there is no thread associated with the TID, if the thread is joined or detached, if no TID is specified or if the specified TID is undef.

指定されたスレッドに関連するアクティブな threads オブジェクトを返します。 もし TID で指定されたスレッドがない場合、join や detach されている場合、 TID が指定されていない場合、指定された TID が undef の 場合、メソッドは undef を返します。

threads->yield()

This is a suggestion to the OS to let this thread yield CPU time to other threads. What actually happens is highly dependent upon the underlying thread implementation.

このスレッドが他のスレッドに CPU 時間を譲ってもいいということを OS に 示唆します。 実際に起こることは、基になっているスレッド実装に大きく依存しています。

You may do use threads qw(yield), and then just use yield() in your code.

コード内では、use threads qw(yield) してから、単に yield() を 使えます。

threads->list()
threads->list(threads::all)
threads->list(threads::running)
threads->list(threads::joinable)

With no arguments (or using threads::all) and in a list context, returns a list of all non-joined, non-detached threads objects. In a scalar context, returns a count of the same.

引数なしで (または threads::all を使って) リストコンテキストの場合、 join されておらず、detach されていない全ての threads オブジェクトの リストを返します。 スカラコンテキストでは、上述のものの数を返します。

With a true argument (using threads::running), returns a list of all non-joined, non-detached threads objects that are still running.

引数が の (または threads::running を使った) 場合、 join されておらず、detach されていない、まだ実行中の threads オブジェクトのリストを返します。

With a false argument (using threads::joinable), returns a list of all non-joined, non-detached threads objects that have finished running (i.e., for which ->join() will not block).

引数が の (または threads::joinable を使った) 場合、 join されておらず、detach されていない、実行が終了した (つまり ->join()ブロック されない) threads オブジェクトの リストを返します。

$thr1->equal($thr2)

Tests if two threads objects are the same thread or not. This is overloaded to the more natural forms:

2 つのスレッドオブジェクトが同じスレッドかどうかをテストします。 これはより自然な形にオーバーロードされます:

    if ($thr1 == $thr2) {
        print("Threads are the same\n");
    }
    # or
    if ($thr1 != $thr2) {
        print("Threads differ\n");
    }

(Thread comparison is based on thread IDs.)

(スレッドの比較はスレッド ID を基にします。)

async BLOCK;

async creates a thread to execute the block immediately following it. This block is treated as an anonymous subroutine, and so must have a semicolon after the closing brace. Like threads->create(), async returns a threads object.

async はその直後に続くブロックを実行するスレッドを生成します。 このブロックは無名サブルーチンとして扱われるので、閉じ大括弧の後に セミコロンをつけなければなりません。 threads->create() 同様、asyncthreads オブジェクトを返します。

$thr->error()

Threads are executed in an eval context. This method will return undef if the thread terminates normally. Otherwise, it returns the value of $@ associated with the thread's execution status in its eval context.

スレッドは 無効 コンテキストで実行されます。 このメソッドは、スレッドが 普通に 終了した場合は undef を返します。 さもなければ、スレッドの実行状態に関連づけられた $@ の値を 無効 コンテキストで返します。

$thr->_handle()

This private method returns the memory location of the internal thread structure associated with a threads object. For Win32, this is a pointer to the HANDLE value returned by CreateThread (i.e., HANDLE *); for other platforms, it is a pointer to the pthread_t structure used in the pthread_create call (i.e., pthread_t *).

この プライベート メソッドは、スレッドオブジェクトに関連づけられた 内部スレッド構造体のメモリ位置を返します。 Win32 では、これは CreateThread から返される HANDLE 値へのポインタ (つまり HANDLE *) です; その他のプラットフォームでは、 pthread_create 呼び出しで使われる pthread_t 構造体へのポインタ (つまり pthread_t *) です。

This method is of no use for general Perl threads programming. Its intent is to provide other (XS-based) thread modules with the capability to access, and possibly manipulate, the underlying thread structure associated with a Perl thread.

このメソッドは、一般的な Perl スレッドプログラミングには無用です。 このメソッドの目的は、その他の (XS ベースの) スレッドモジュールが、 Perl スレッドと関連づけられている基礎となるスレッド構造体へのアクセスおよび おそらくは操作を可能にすることです。

threads->_handle()

Class method that allows a thread to obtain its own handle.

スレッドが自身の handle を得るためのクラスメソッドです。

スレッドの終了

The usual method for terminating a thread is to return() from the entry point function with the appropriate return value(s).

スレッドを終了するための通常の手法は、エントリポイント関数で 適切な返り値と共に return() を使うことです。

threads->exit()

If needed, a thread can be exited at any time by calling threads->exit(). This will cause the thread to return undef in a scalar context, or the empty list in a list context.

もし必要なら、スレッドはいつでも threads->exit() を 呼び出すことで終了させることが出来ます。 これにより、スレッドはスカラコンテキストでは undef を返し、 リストコンテキストでは空リストを返します。

When called from the main thread, this behaves the same as exit(0).

main スレッドから呼び出されると、exit(0) と同様に振る舞います。

threads->exit(status)

When called from a thread, this behaves like threads->exit() (i.e., the exit status code is ignored).

スレッドから呼び出されると、threads->exit() と同様に振る舞います (つまり、status 終了コードは無視されます)。

When called from the main thread, this behaves the same as exit(status).

main スレッドから呼び出されると、exit(status) と同様に振る舞います。

die()

Calling die() in a thread indicates an abnormal exit for the thread. Any $SIG{__DIE__} handler in the thread will be called first, and then the thread will exit with a warning message that will contain any arguments passed in the die() call.

スレッドでの die() の呼び出しは、スレッドの異常終了を意味します。 まずスレッドでの $SIG{__DIE__} ハンドラが呼び出され、 それからスレッドは die() 呼び出しに渡された引数による警告メッセージと 共に終了します。

exit(status)

Calling exit() inside a thread causes the whole application to terminate. Because of this, the use of exit() inside threaded code, or in modules that might be used in threaded applications, is strongly discouraged.

スレッドの内部で exit() を呼び出すと、 アプリケーション全体が終了します。 これのことにより、スレッドコード内部や、スレッド化された アプリケーションで使われるかも知れないモジュールでの exit() の使用は 強く非推奨です。

If exit() really is needed, then consider using the following:

もし本当に exit() が必要なら、以下を使うことを考えてください:

    threads->exit() if threads->can('exit');   # Thread friendly
    exit(status);
use threads 'exit' => 'threads_only'

This globally overrides the default behavior of calling exit() inside a thread, and effectively causes such calls to behave the same as threads->exit(). In other words, with this setting, calling exit() causes only the thread to terminate.

これはスレッド内での exit() 呼び出しのデフォルトの振る舞いをグローバルに 上書きし、事実上このような呼び出しを threads->exit() と同じ 振る舞いにします。 言い換えると、この設定によって、exit() を呼び出したときにスレッドだけを 終了させます。

Because of its global effect, this setting should not be used inside modules or the like.

これはグローバルな効果を持つので、この設定はモジュールのようなものの内部では 使うべきではありません。

The main thread is unaffected by this setting.

main スレッドはこの設定の影響を受けません。

threads->create({'exit' => 'thread_only'}, ...)

This overrides the default behavior of exit() inside the newly created thread only.

これは新しく作られたスレッドの内側でだけ exit() のデフォルトの 振る舞いを上書きします。

$thr->set_thread_exit_only(boolean)

This can be used to change the exit thread only behavior for a thread after it has been created. With a true argument, exit() will cause only the thread to exit. With a false argument, exit() will terminate the application.

これは、スレッドの スレッドだけ終了 の振る舞いを、スレッドが作られた 後で変更するために使われます。 の値を渡すと、exit() によってスレッドだけが終了します。 の値を渡すと、exit() によってアプリケーションが終了します。

The main thread is unaffected by this call.

main スレッドはこの呼び出しの影響を受けません。

threads->set_thread_exit_only(boolean)

Class method for use inside a thread to change its own behavior for exit().

exit() の振る舞いを変えるためにスレッドの内側で使うための クラスメソッドです。

The main thread is unaffected by this call.

main スレッドはこの呼び出しの影響を受けません。

スレッドの状態

The following boolean methods are useful in determining the state of a thread.

以下の真偽値メソッドはスレッドの 状態 を決定するのに便利です。

$thr->is_running()

Returns true if a thread is still running (i.e., if its entry point function has not yet finished or exited).

スレッドがまだ実行されている(つまり、そのエントリポイント関数がまだ完了または 終了していない)なら真を返します。

$thr->is_joinable()

Returns true if the thread has finished running, is not detached and has not yet been joined. In other words, the thread is ready to be joined, and a call to $thr->join() will not block.

スレッドが実行を完了していて、detach も join もされていないなら真を返します。 言い換えると、このスレッドは join する準備が出来ていて、 $thr->join() の呼び出しは ブロック されません。

$thr->is_detached()

Returns true if the thread has been detached.

スレッドが detach されたなら真を返します。

threads->is_detached()

Class method that allows a thread to determine whether or not it is detached.

スレッドが detach されているかどうかを決定できるようにするための クラスメソッドです。

スレッドのコンテキスト

As with subroutines, the type of value returned from a thread's entry point function may be determined by the thread's context: list, scalar or void. The thread's context is determined at thread creation. This is necessary so that the context is available to the entry point function via wantarray(). The thread may then specify a value of the appropriate type to be returned from ->join().

サブルーチンと同様、スレッドのエントリポイント関数から返される値の型は スレッドの コンテキスト (リスト、スカラ、無効のいずれか) によって 決定されます。 スレッドのコンテキストはスレッド作成時に決定されます。 これは、コンテキストをエントリポイント関数から wantarray() を使って利用可能にするために必要です。 それからスレッドは ->join() から返される適切な型の値を指定します。

明示的なコンテキスト

Because thread creation and thread joining may occur in different contexts, it may be desirable to state the context explicitly to the thread's entry point function. This may be done by calling ->create() with a hash reference as the first argument:

スレッドの作成とスレッドの join は異なったコンテキストで 行われるかもしれないので、スレッドのエントリポイント関数で明示的に コンテキストを宣言することが望ましいです。 これは最初の引数としてハッシュリファレンスを指定した ->create() を 呼び出すことで行えます:

    my $thr = threads->create({'context' => 'list'}, \&foo);
    ...
    my @results = $thr->join();

In the above, the threads object is returned to the parent thread in scalar context, and the thread's entry point function foo will be called in list (array) context such that the parent thread can receive a list (array) from the ->join() call. ('array' is synonymous with 'list'.)

上述の場合、スレッドオブジェクトは親スレッドにスカラコンテキストで 返され、スレッドのエントリポイント関数 foo はリスト(配列)コンテキストで 予備されるので、親スレッドは ->join() 呼び出しからリスト(配列)を 受け取ります。 ('array''list' の同義語です。)

Similarly, if you need the threads object, but your thread will not be returning a value (i.e., void context), you would do the following:

同様に、もしスレッドオブジェクトが必要だけれども、スレッドが値を返さない (つまり 無効 コンテキスト) 場合、以下のようにします:

    my $thr = threads->create({'context' => 'void'}, \&foo);
    ...
    $thr->join();

The context type may also be used as the key in the hash reference followed by a true value:

コンテキスト型はまた、ハッシュリファレンスの キー に引き続いて の 値としても使えます:

    threads->create({'scalar' => 1}, \&foo);
    ...
    my ($thr) = threads->list();
    my $result = $thr->join();

暗黙のコンテキスト

If not explicitly stated, the thread's context is implied from the context of the ->create() call:

明示的に宣言されない場合、スレッドのコンテキストは ->create() 呼び出しのコンテキストになります:

    # Create thread in list context
    my ($thr) = threads->create(...);

    # Create thread in scalar context
    my $thr = threads->create(...);

    # Create thread in void context
    threads->create(...);

$thr->wantarray()

This returns the thread's context in the same manner as wantarray().

これは wantarray() と同じ方法でスレッドの コンテキストを返します。

threads->wantarray()

Class method to return the current thread's context. This returns the same value as running wantarray() inside the current thread's entry point function.

現在のスレッドのコンテキストを返すクラスメソッドです。 現在のスレッドのエントリポイント関数の内側で wantarray() を実行するのと同じ値を返します。

スレッドのスタックサイズ

The default per-thread stack size for different platforms varies significantly, and is almost always far more than is needed for most applications. On Win32, Perl's makefile explicitly sets the default stack to 16 MB; on most other platforms, the system default is used, which again may be much larger than is needed.

デフォルトのスレッド毎のスタックサイズはプラットフォームによって大きく異なり、 ほとんど常にほとんどのアプリケーションが必要な量よりはるかに多いです。 Win32 では、Perl の makefile は明示的にデフォルトのスタックを 16 MB に 指定しています; その他のほとんどのシステムでは、システムのデフォルトが 使われますが、やはり必要な量よりはるかに多いです。

By tuning the stack size to more accurately reflect your application's needs, you may significantly reduce your application's memory usage, and increase the number of simultaneously running threads.

スタックサイズをアプリケーションのニーズにより正確に反映させることにより、 アプリケーションのメモリ使用量を著しく減少させ、同時実行スレッド数を 増やすことができるかもしれません。

Note that on Windows, address space allocation granularity is 64 KB, therefore, setting the stack smaller than that on Win32 Perl will not save any more memory.

従って、アドレス空間配置の粒度が 64 KB である Windows では、Win32 Perl で これより小さい値にスタックを設定してもメモリを節約できないことに 注意してください。

threads->get_stack_size();

Returns the current default per-thread stack size. The default is zero, which means the system default stack size is currently in use.

現在のデフォルトのスレッド毎のスタックサイズを返します。 デフォルトは 0 で、これはシステムのデフォルトスタックサイズを 使っていることを示します。

$size = $thr->get_stack_size();

Returns the stack size for a particular thread. A return value of zero indicates the system default stack size was used for the thread.

特定のスレッドのスタックサイズを返します。 返り値 0 は、そのスレッドでシステムデフォルトのスタックサイズが 使われていることを示します。

$old_size = threads->set_stack_size($new_size);

Sets a new default per-thread stack size, and returns the previous setting.

新しいデフォルトのスレッド毎のスタックサイズを設定し、以前の設定を 返します。

Some platforms have a minimum thread stack size. Trying to set the stack size below this value will result in a warning, and the minimum stack size will be used.

最小スレッドスタックサイズがあるプラットフォームもあります。 その値よりスタックサイズを小さくしようとすると警告が出て、最小 スタックサイズが使われます。

Some Linux platforms have a maximum stack size. Setting too large of a stack size will cause thread creation to fail.

最大スタックサイズのある Linux プラットフォームもあります。 大きすぎるスタックサイズを設定するとスレッド作成に失敗します。

If needed, $new_size will be rounded up to the next multiple of the memory page size (usually 4096 or 8192).

必要なら、$new_size は次のメモリページサイズ(普通は4096 か 8192)倍数に 切り上げられます。

Threads created after the stack size is set will then either call pthread_attr_setstacksize() (for pthreads platforms), or supply the stack size to CreateThread() (for Win32 Perl).

スタックサイズが設定された後に作られたスレッドは pthread_attr_setstacksize() を呼び出す (pthreads プラットフォームの 場合)CreateThread() にスタックサイズを渡します (Win32 Perl の場合)

(Obviously, this call does not affect any currently extant threads.)

(明らかに、この呼び出しは既に存在するスレッドには影響を与えません。)

use threads ('stack_size' => VALUE);

This sets the default per-thread stack size at the start of the application.

これはアプリケーションの開始時にスタック単位のデフォルトのスタックサイズを 設定します。

$ENV{'PERL5_ITHREADS_STACK_SIZE'}

The default per-thread stack size may be set at the start of the application through the use of the environment variable PERL5_ITHREADS_STACK_SIZE:

デフォルトのスレッド毎のスタックサイズは環境変数 PERL5_ITHREADS_STACK_SIZE を使ってアプリケーションの開始時に設定できます:

    PERL5_ITHREADS_STACK_SIZE=1048576
    export PERL5_ITHREADS_STACK_SIZE
    perl -e'use threads; print(threads->get_stack_size(), "\n")'

This value overrides any stack_size parameter given to use threads. Its primary purpose is to permit setting the per-thread stack size for legacy threaded applications.

この値は use threads に与えられる stack_size 引数で上書きできます。 主な目的はレガシーなスレッドアプリケーションでスレッド毎のスタックサイズを 設定できるようにすることです。

threads->create({'stack_size' => VALUE}, FUNCTION, ARGS)

To specify a particular stack size for any individual thread, call ->create() with a hash reference as the first argument:

個々のスレッドの個別のスタックサイズを指定するには、最初の引数として ハッシュリファレンスを指定して ->create() を呼び出します:

    my $thr = threads->create({'stack_size' => 32*4096}, \&foo, @args);
$thr2 = $thr1->create(FUNCTION, ARGS)

This creates a new thread ($thr2) that inherits the stack size from an existing thread ($thr1). This is shorthand for the following:

これは既に存在するスレッド ($thr1) からスタックサイズを継承して新しい スレッド ($thr2) を作成します。 これは以下のものの短縮形です:

    my $stack_size = $thr1->get_stack_size();
    my $thr2 = threads->create({'stack_size' => $stack_size}, FUNCTION, ARGS);

スレッドとシグナル

When safe signals is in effect (the default behavior - see "Unsafe signals" for more details), then signals may be sent and acted upon by individual threads.

安全なシグナルが有効なとき (デフォルトの振る舞いです - さらなる 詳細については "Unsafe signals" を参照してください)、シグナルは それぞれのスレッドに対して送られて動作します。

$thr->kill('SIG...');

Sends the specified signal to the thread. Signal names and (positive) signal numbers are the same as those supported by kill(). For example, 'SIGTERM', 'TERM' and (depending on the OS) 15 are all valid arguments to ->kill().

指定されたシグナルをスレッドに送ります。 シグナル名と(正の)シグナル番号は kill() で 対応しているものと同じです。 例えば、'SIGTERM', 'TERM' と (OS に依存しますが) 15 は全て ->kill() への妥当な引数です。

Returns the thread object to allow for method chaining:

メソッドチェーンができるように、スレッドオブジェクトを返します:

    $thr->kill('SIG...')->join();

Signal handlers need to be set up in the threads for the signals they are expected to act upon. Here's an example for cancelling a thread:

シグナルハンドラは対応することを想定しているシグナルに対してスレッドで 設定される必要があります。 以下はスレッドを キャンセルする 例です:

    use threads;

    sub thr_func
    {
        # Thread 'cancellation' signal handler
        $SIG{'KILL'} = sub { threads->exit(); };

        ...
    }

    # Create a thread
    my $thr = threads->create('thr_func');

    ...

    # Signal the thread to terminate, and then detach
    # it so that it will get cleaned up automatically
    $thr->kill('KILL')->detach();

Here's another simplistic example that illustrates the use of thread signalling in conjunction with a semaphore to provide rudimentary suspend and resume capabilities:

以下は基本的な 中断再開 の機能を提供するためにスレッドの シグナルをセマフォと組み合わせた使い方を示すための単純化されたもう一つの 例です:

    use threads;
    use Thread::Semaphore;

    sub thr_func
    {
        my $sema = shift;

        # Thread 'suspend/resume' signal handler
        $SIG{'STOP'} = sub {
            $sema->down();      # Thread suspended
            $sema->up();        # Thread resumes
        };

        ...
    }

    # Create a semaphore and pass it to a thread
    my $sema = Thread::Semaphore->new();
    my $thr = threads->create('thr_func', $sema);

    # Suspend the thread
    $sema->down();
    $thr->kill('STOP');

    ...

    # Allow the thread to continue
    $sema->up();

CAVEAT: The thread signalling capability provided by this module does not actually send signals via the OS. It emulates signals at the Perl-level such that signal handlers are called in the appropriate thread. For example, sending $thr->kill('STOP') does not actually suspend a thread (or the whole process), but does cause a $SIG{'STOP'} handler to be called in that thread (as illustrated above).

警告: このモジュールによって提供されているスレッドへのシグナル機能は 実際には OS 経由でシグナルを送っていません。 シグナルハンドラが適切なスレッドで呼び出されるように Perl レベルでシグナルを エミュレート しています。 例えば、$thr->kill('STOP') は実際にはスレッド(またはプロセス全体)を 停止させませんが、(上述したように) 対象のスレッドの $SIG{'STOP'} ハンドラが呼び出されます。

As such, signals that would normally not be appropriate to use in the kill() command (e.g., kill('KILL', $$)) are okay to use with the ->kill() method (again, as illustrated above).

そのため、普通は kill() コマンドでの使用が適切ではないようなシグナル (例えば kill('KILL', $$))) は ->kill() メソッドで使っても (再び上述したように)問題ありません。

Correspondingly, sending a signal to a thread does not disrupt the operation the thread is currently working on: The signal will be acted upon after the current operation has completed. For instance, if the thread is stuck on an I/O call, sending it a signal will not cause the I/O call to be interrupted such that the signal is acted up immediately.

同様に、スレッドにシグナルを送ってもスレッドが今処理している操作を 妨害しません: シグナルは現在の処理が終了した後に処理されます。 例えば、スレッドが I/O 呼び出して 固まっている なら、シグナルが直ちに 処理されるように I/O 呼び出しを中断はしません。

Sending a signal to a terminated thread is ignored.

終了したスレッドへのシグナル送信は無視されます。

警告

Perl exited with active threads:

If the program exits without all threads having either been joined or detached, then this warning will be issued.

全てのスレッドが join されるか detach される前にプログラムが終了した場合、 この警告が発生します。

NOTE: If the main thread exits, then this warning cannot be suppressed using no warnings 'threads'; as suggested below.

注意: main スレッドが存在しているなら、後に示唆しているようにこの警告は no warnings 'threads'; を使って抑制できません。

Thread creation failed: pthread_create returned #

See the appropriate man page for pthread_create to determine the actual cause for the failure.

失敗の実際の原因を決定するには pthread_create の適切な man ページを 参照してください。

Thread # terminated abnormally: ...

A thread terminated in some manner other than just returning from its entry point function, or by using threads->exit(). For example, the thread may have terminated because of an error, or by using die.

スレッドが単にエントリポイント関数から返ったか threads->exit() を 使った以外の何らかの方法で終了しました。 例えば、エラーや die の使用によってスレッドが終了しました。

Using minimum thread stack size of #

Some platforms have a minimum thread stack size. Trying to set the stack size below this value will result in the above warning, and the stack size will be set to the minimum.

最低スレッドスタックサイズがあるプラットフォームもあります。 スタックサイズをその値以下に設定しようとするとこの警告が出て、 スタックサイズは最小値に設定されます。

Thread creation failed: pthread_attr_setstacksize(SIZE) returned 22

The specified SIZE exceeds the system's maximum stack size. Use a smaller value for the stack size.

指定された SIZE がシステムの最大スタックサイズを超えています。 スタックサイズとしてより小さい値を使ってください。

If needed, thread warnings can be suppressed by using:

もし必要なら、スレッドの警告は以下のものを:

    no warnings 'threads';

in the appropriate scope.

適切なスコープで使うことで抑制できます。

エラー

This Perl not built to support threads

The particular copy of Perl that you're trying to use was not built using the useithreads configuration option.

使おうとしている Perl が useithreads 設定オプションを使って ビルドされていません。

Having threads support requires all of Perl and all of the XS modules in the Perl installation to be rebuilt; it is not just a question of adding the threads module (i.e., threaded and non-threaded Perls are binary incompatible.)

スレッド対応にするためには Perl の全てと Perl インストールの全ての XS モジュールを再ビルドする必要があります; これは threads モジュールを 追加するためだけではありません (つまり、スレッド対応 Perl と非対応 Perl は バイナリ互換性がありません。)

Cannot change stack size of an existing thread

The stack size of currently extant threads cannot be changed, therefore, the following results in the above error:

現在既にあるスレッドのスタックサイズは変更できないので、以下のようなものは 上述のエラーになります:

    $thr->set_stack_size($size);
Cannot signal threads without safe signals

Safe signals must be in effect to use the ->kill() signalling method. See "Unsafe signals" for more details.

->kill() シグナルメソッドを使うには安全なシグナルが 有効でなければなりません。 さらなる詳細については "Unsafe signals" を参照してください。

Unrecognized signal name: ...

The particular copy of Perl that you're trying to use does not support the specified signal being used in a ->kill() call.

使おうとしている Perl が ->kill() 呼び出しで使おうとしているシグナルに 対応していません。

バグと制限

Before you consider posting a bug report, please consult, and possibly post a message to the discussion forum to see if what you've encountered is a known problem.

バグ報告を投稿することを考える前に、まず相談してください; そしてできれば 遭遇したものが既知の問題かどうかを見るために議論フォーラムにメッセージを 投稿してください。

Thread-safe modules

(スレッドセーフなモジュール)

See "Making your module threadsafe" in perlmod when creating modules that may be used in threaded applications, especially if those modules use non-Perl data, or XS code.

スレッド対応アプリケーションで使われるかもしれないモジュールを作るとき、 とくにモジュールが非 Perl データや XS コードを使っているときは、 "Making your module threadsafe" in perlmod を参照してください。

Using non-thread-safe modules

(非スレッドセーフなモジュールを使う)

Unfortunately, you may encounter Perl modules that are not thread-safe. For example, they may crash the Perl interpreter during execution, or may dump core on termination. Depending on the module and the requirements of your application, it may be possible to work around such difficulties.

残念ながら、スレッドセーフ ではない Perl モジュールに 遭遇するかもしれません。 例えば、実行中に Perl インタプリタがクラッシュしたり、コアダンプして 終了したりするかもしれません。 モジュールとアプリケーションの必要事項に依存して、このような問題を 回避できることがあります。

If the module will only be used inside a thread, you can try loading the module from inside the thread entry point function using require (and import if needed):

モジュールがスレッドの中でだけ使われているなら、スレッドエントリ関数の 内側から require (および必要なら import) を使ってモジュールを 読み込んでみてください:

    sub thr_func
    {
        require Unsafe::Module
        # Unsafe::Module->import(...);

        ....
    }

If the module is needed inside the main thread, try modifying your application so that the module is loaded (again using require and ->import()) after any threads are started, and in such a way that no other threads are started afterwards.

モジュールが main スレッドの内側で必要なら、スレッドを開始してから (再び require->import() を使って) モジュールが 読み込まれるように、そしてその後他のスレッドが開始しないように アプリケーションを修正してみてください。

If the above does not work, or is not adequate for your application, then file a bug report on http://rt.cpan.org/Public/ against the problematic module.

上述のものが動作しないか、アプリケーションに適切でないなら、問題のある モジュールに対して http://rt.cpan.org/Public/ にバグ報告を 登録してください。

Current working directory

(カレントワーキングディレクトリ)

On all platforms except MSWin32, the setting for the current working directory is shared among all threads such that changing it in one thread (e.g., using chdir()) will affect all the threads in the application.

MSWin32 以外の全てのプラットフォームでは、カレントワーキングディレクトリの 設定は全てのスレッドで共有されるので、あるスレッドでこれを変更する (つまり chdir() を使う) とアプリケーションの全てのスレッドに 影響します。

On MSWin32, each thread maintains its own the current working directory setting.

MSWin32 では、それぞれのカレントワーキングディレクトリ設定を独自に 管理しています。

Environment variables

(環境変数)

Currently, on all platforms except MSWin32, all system calls (e.g., using system() or back-ticks) made from threads use the environment variable settings from the main thread. In other words, changes made to %ENV in a thread will not be visible in system calls made by that thread.

現在のところ、MSWin32 以外の全てのプラットフォームでは、 スレッドによって作られた (system() または逆クォートによる) 全ての system 呼び出しは main スレッドの環境変数設定を使います。 言い換えると、スレッドで行った %ENV への変更は、そのスレッドで作られた system 呼び出しでは見えません。

To work around this, set environment variables as part of the system call. For example:

これを回避するには、system 呼び出しの一部として環境変数をセットします。 例えば:

    my $msg = 'hello';
    system("FOO=$msg; echo \$FOO");   # Outputs 'hello' to STDOUT

On MSWin32, each thread maintains its own set of environment variables.

MSWin32 では、各スレッドでは独自の環境変数集合を管理します。

Parent-child threads

(親-子スレッド)

On some platforms, it might not be possible to destroy parent threads while there are still existing child threads.

プラットフォームによっては、 スレッドがまだ存在している間は スレッドを破壊することができないことがあります。

Creating threads inside special blocks

(特殊ブロックの中でスレッドを作る)

Creating threads inside BEGIN, CHECK or INIT blocks should not be relied upon. Depending on the Perl version and the application code, results may range from success, to (apparently harmless) warnings of leaked scalar, or all the way up to crashing of the Perl interpreter.

BEGIN, CHECK, INIT ブロックの内側でスレッドを作成することを 信頼するべきではありません。 Perl バージョンとアプリケーションコードに依存して、成功から(おそらくは 無害な)リークしたスカラの警告、Perl インタプリタのクラッシュまでさまざまな 結果となります。

Unsafe signals

(安全でないシグナル)

Since Perl 5.8.0, signals have been made safer in Perl by postponing their handling until the interpreter is in a safe state. See "Safe Signals" in perl58delta and "Deferred Signals (Safe Signals)" in perlipc for more details.

Perl 5.8.0 から、インタプリタが 安全な 状態になるまでシグナル操作を 延期することでシグナルはより安全になりました。 さらなる詳細については "Safe Signals" in perl58delta"Deferred Signals (Safe Signals)" in perlipc を参照してください。

Safe signals is the default behavior, and the old, immediate, unsafe signalling behavior is only in effect in the following situations:

安全なシグナルはデフォルトの振る舞いで、古い、即時で、安全でないシグナルの 振る舞いは以下の状況でのみ有効です。

If unsafe signals is in effect, then signal handling is not thread-safe, and the ->kill() signalling method cannot be used.

安全でないシグナルが有効の場合、シグナルの扱いはスレッドセーフではなく、 ->kill() シグナルメソッドは使えません。

Returning closures from threads

(スレッドからクロージャを返す)

Returning closures from threads should not be relied upon. Depending of the Perl version and the application code, results may range from success, to (apparently harmless) warnings of leaked scalar, or all the way up to crashing of the Perl interpreter.

スレッドからクロージャを返すことを信頼するべきではありmせん。 Perl バージョンとアプリケーションコードに依存して、成功から(おそらくは 無害な)リークしたスカラの警告、Perl インタプリタのクラッシュまでさまざまな 結果となります。

Returning objects from threads

(スレッドからオブジェクトを返す)

Returning objects from threads does not work. Depending on the classes involved, you may be able to work around this by returning a serialized version of the object (e.g., using Data::Dumper or Storable), and then reconstituting it in the joining thread. If you're using Perl 5.10.0 or later, and if the class supports shared objects, you can pass them via shared queues.

スレッドからオブジェクトを返すのは動作しません。 使うクラスに依存して、(例えば Data::DumperStorable を使って) 直列化されたオブジェクトを返して、join したスレッドでこれを再構成することで これを回避できることがあります。 Perl 5.10.0 以降を使っていて、クラスが 共有オブジェクト に対応しているなら、 共有キュー 経由で渡すことができます。

END blocks in threads

(スレッドの END ブロック)

It is possible to add END blocks to threads by using require or eval with the appropriate code. These END blocks will then be executed when the thread's interpreter is destroyed (i.e., either during a ->join() call, or at program termination).

適切なコードで requireeval を使うことでスレッドに END ブロック を追加することは可能です。 これらの END ブロックはスレッドインタプリタが破壊される (つまり ->join() の呼び出しの間かプログラムが終了する)ときに 実行されます。

However, calling any threads methods in such an END block will most likely fail (e.g., the application may hang, or generate an error) due to mutexes that are needed to control functionality within the threads module.

しかし、END ブロックのような中で threads メソッドを呼び出すと、 threads モジュール内部の機能を制御するために必要なミューテックスのために ほぼ間違いなく 失敗 (例えばアプリケーションがハングしたりエラーが 発生したり)します。

For this reason, the use of END blocks in threads is strongly discouraged.

この理由により、スレッド中の END の使用は 強く 非推奨です。

Perl Bugs and the CPAN Version of threads

(Perl のバグと CPAN 版の threads)

Support for threads extends beyond the code in this module (i.e., threads.pm and threads.xs), and into the Perl interpreter itself. Older versions of Perl contain bugs that may manifest themselves despite using the latest version of threads from CPAN. There is no workaround for this other than upgrading to the latest version of Perl.

スレッドの対応は このモジュール (つまり threads.pmthreads.xs) のコードを超えて Perl インタプリタ自身に拡張されます。 より古いバージョンの Perl には CPAN から最新版の threads を使っているにも 関わらず自分自身を示すというバグがあります。 Perl を最新版にアップグレードする以外に回避方法はありません。

Even with the latest version of Perl, it is known that certain constructs with threads may result in warning messages concerning leaked scalars or unreferenced scalars. However, such warnings are harmless, and may safely be ignored.

最新版の Perl でも、スレッドとある種の構造はリークしたスカラや 参照されていないスカラ内観する警告メッセージが出ることがあります。 しかし、このような警告は無害で、安全に無視できます。

You can search for threads related bug reports at http://rt.cpan.org/Public/. If needed submit any new bugs, problems, patches, etc. to: http://rt.cpan.org/Public/Dist/Display.html?Name=threads

threads 関連のバグ報告を http://rt.cpan.org/Public/ で探せます。 新しいバグ、問題、パッチなどを投稿する必要があるなら: http://rt.cpan.org/Public/Dist/Display.html?Name=threads

必要条件

Perl 5.8.0 or later

Perl 5.8.0 以降

SEE ALSO

CPAN の threads ディスカッションフォーラム: http://www.cpanforum.com/dist/threads

threads の注釈付き POD: http://annocpan.org/~JDHEDDEN/threads-1.72/threads.pm

ソースレポジトリ: http://code.google.com/p/threads-shared/

threads::shared, perlthrtut

http://www.perl.com/pub/a/2002/06/11/threads.htmlhttp://www.perl.com/pub/a/2002/09/04/threads.html

Perl スレッドメーリングリスト: http://lists.cpan.org/showlist.cgi?name=iThreads

スタックサイズの議論: http://www.perlmonks.org/?node_id=532956

作者

Artur Bergman <sky AT crucially DOT net>

CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>

ライセンス

threads is released under the same license as Perl.

謝辞

Richard Soderberg <perl AT crystalflame DOT net> - Helping me out tons, trying to find reasons for races and other weird bugs!

Simon Cozens <simon AT brecon DOT co DOT uk> - Being there to answer zillions of annoying questions

Rocco Caputo <troc AT netrus DOT net>

Vipul Ved Prakash <mail AT vipul DOT net> - Helping with debugging

Dean Arnold <darnold AT presicient DOT com> - Stack size API