1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #!/usr/bin/perl # use threads; use threads::shared; use strict; my $var :shared = 0; # use :share tag to define my @array :shared = (); # use :share tag to define my %hash = (); share(%hash); # use share() funtion to define sub start { $var = 100; @array[0] = 200; @array[1] = 201; $hash{'1'} = 301; $hash{'2'} = 302; } sub verify { sleep(1); # make sure thread t1 execute firstly printf("var = $var\n"); # var=100 for(my $i = 0; $i < scalar(@array); $i++) { printf("array[$i] = $array[$i]\n"); # array[0]=200; array[1]=201 } foreach my $key ( sort( keys(%hash) ) ) { printf("hash{$key} = $hash{$key}\n"); # hash{1}=301; hash{2}=302 } } my $t1 = threads->create( \&start ); my $t2 = threads->create( \&verify ); $t1->join(); $t2->join(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | use threads::shared; # in thread 1 { lock( $share ); # lock for 3 seconds sleep(3); # other threads can not lock again } # unlock implicitly now after the block # in thread 2 { lock($share); # will be blocked, as already locked by thread 1 $share++; # after thread 1 quit from the block } # unlock implicitly now after the block |
1 2 3 4 5 6 7 8 9 10 11 12 13 | use threads; use threads::shared; { lock(@share); # the array has been locked lock(%hash); # the hash has been locked sleep(3); # other threads can not lock again } { lock($share[1]); # error will occur lock($hash{key}); # error will occur } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | use threads; use threads::shared; # in thread 1 { lock($a); # lock for 3 seconds sleep(3); # other threads can not lock again lock($b); # dead lock here } # in thread 2 { lock($b); # will be blocked, as already locked by thread 1 sleep(3); # after thread 1 quit from the block lock($a); # dead lock here } |
1 2 3 4 5 6 7 8 | use threads; use threads::shared; use Thread::Semaphore; my $s = Thread::Semaphore->new(); $s->down(); # P operation ... $s->up(); # V operation |
1 2 3 4 5 6 7 8 9 10 | use threads; use Thread::Semaphore; my $s = Thread::Semaphore->new(5); printf("s = " . ${$s} . "\n"); # s = 5 $s->down(3); printf("s = " . ${$s} . "\n"); # s = 2 ... $s->up(4); printf("s = " . ${$s} . "\n"); # s = 6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #!/usr/bin/perl # use threads; use Thread:ueue; my $q = Thread:ueue->new(); sub produce { my $name = shift; while(1) { my $r = int(rand(100)); $q->enqueue($r); printf("$name produce $r\n"); sleep(int(rand(3))); } } sub consume { my $name = shift; while(my $r = $q->dequeue()) { printf("consume $r\n"); } } my $producer1 = threads->create(\&produce, "producer1"); my $producer2 = threads->create(\&produce, "producer2"); my $consumer1 = threads->create(\&consume, "consumer2"); $producer1->join(); $producer2->join(); $consumer1->join(); |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |