הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Threading

use threads;
 
use Modern::Perl;
 
sub hello {
        my $name = shift || "Anonymous";
        return sub { say "I Am $name" }
}
 
my $t1 = threads->create(hello("Bill"));
my $t2 = threads->create(hello("Ted"));
 
$t1->join;
$t2->join;
 
say "And we\'re... WYLD STALLYNS!";
use Modern::Perl;
use threads;
use threads::shared;
use List::Util qw(reduce);
 
sub sum {
        my ($start, $end) = @_;
        local ($a, $b);
        my $sum = reduce { $a + $b } $start..$end;
 
        return $sum;
}
 
my $t1 = threads->create('sum',1,10000);
my $t2 = threads->create('sum',10000,20000);
 
my $s1 = $t1->join;
my $s2 = $t2->join;
 
say "Total sum = ", $s1 + $s2;
use strict;
use threads;
 
sub random_wait {
        my $tid = threads->tid();
        my $n = int(rand(4));
        print "$tid: waiting $n seconds\n";
        sleep($n);
}
 
my @threads = map {threads->create ('random_wait')} (1..10);
print "starting to join threads\n";
 
my @results = map {$_->join() } @threads;
 
print "All threads joined, results: @results\n";
 
use Modern::Perl;
 
use threads;
use threads::shared;
 
my $o :shared = 1;
my $m = 5;
 
sub increase {
	while(1) {
		say "Increase: o = $o, m = $m";
		$o += 1;
		$m += 1;
		sleep(1);
	}
}
 
sub decrease {
	while(1) {
		say "Decrease: o = $o, m = $m";
		$o -= 1;
		$m -= 1;
		sleep(2);
	}
}
 
my $t1 = threads->create('increase');
my $t2 = threads->create('decrease');
 
$t1->join;
 
course: