- #!/usr/bin/perl
- use strict;
- use threads;
- use threads::shared;
- my $var=100;
- share($var); #### 共享变量进程和个线程之间
- my $t1 = threads -> create (\&thread_child, "T1");
- sleep 1;
- my $t2 = threads -> create (\&thread_child, "T2");
- print "do something in the main thread.......\n";
- sleep 1;
- &thread_child("main_thread");
- $t1 -> detach();
- $t2 -> detach();
- #print "T1 return the name is : $t1_res.....\n";
- #print "T2 return the name is : $t2_res.....\n";
- sub thread_child
- {
- my @name =@_;
- print "@name var is $var......\n";
- $var ++;
-
- }
上锁共享变量
- #!/usr/bin/perl
- use strict;
- use threads;
- use threads::shared;
- use Thread::Semaphore;
- my $var=100;
- share($var);
- my $t1 = threads -> create (\&thread_child, "T1");
- my $t2 = threads -> create (\&thread_child, "T2");
- print "do something in the main thread.......\n";
- &thread_child("main_thread");
- $t1 -> detach();
- $t2 -> detach();
- sub thread_child
- {
- my @name =@_;
- {
- lock ($var); ## 给var变量上锁,当块结束的时候,锁也就没有了
- print "@name var is $var......\n";
- $var ++;
- }
-
- }
线程中的信号量,也就是PV操作
- #!/usr/bin/perl
- use strict;
- use threads;
- use threads::shared;
- use Thread::Semaphore; ## 线程信号量模块
- my $var=100;
- share($var);
- my $s = Thread:Semaphore->new();
- my $t1 = threads -> create (\&thread_child, "T1");
- my $t2 = threads -> create (\&thread_child, "T2");
- print "do something in the main thread.......\n";
- &thread_child("main_thread");
- $t1 -> detach();
- $t2 -> detach();
- sub thread_child
- {
- my @name =@_;
- $s->down(); P操作
- print "@name var is $var......\n";
- $var ++;
- $s->up(); V操作
- }
阅读(3631) | 评论(0) | 转发(0) |