Kawaninon.com

写真やサンプルプログラムなど、
日々の気になった出来事をメモしてる個人的なブログです。

マルチスレッドの処理をPerl言語のthreadsで生成

Perlモジュールのthreadsを使用して、マルチスレッドの処理を実行しました。threadsは、Perlの標準モジュールなので再度インストール必要は有りません。)

#!/opt/local/bin/perl
 
use strict;
use warnings;
use utf8;
use threads;
use Time::HiRes;
 
print "Content-type: text/html; charset=utf-8\n\n";
 
my $threads = sub
{
    my $name = shift;
    for ('A' .. 'E')
    {
        print +("${name} - ${_}"), "\n";
        Time::HiRes::sleep(0.1);
        threads->yield();
    }
};
 
my $first  = threads->new(\&$threads, "1");
my $second = threads->new(\&$threads, "2");
my $third  = threads->new(\&$threads, "3");
my $fourth = threads->new(\&$threads, "4");
my $fifth  = threads->new(\&$threads, "5");
 
$first->join;
$second->join;
$third->join;
$fourth->join;
$fifth->join;
 
exit;1 - A
1 - B
2 - A
1 - C
2 - B
1 - D
2 - C
1 - E
3 - A
2 - D
3 - B
2 - E
3 - C
4 - A
3 - D
4 - B
5 - A
3 - E
4 - C
5 - B
4 - D
5 - C
4 - E
5 - D
5 - E

サンプルコードと出力結果です。マルチスレッドの処理をthreadsモジュールで出力しました。

スポンサーリンク

これらを使ってサイトを運用しています

QRコード

QR Code