Chinaunix首页 | 论坛 | 博客
  • 博客访问: 81122
  • 博文数量: 28
  • 博客积分: 579
  • 博客等级: 中士
  • 技术积分: 245
  • 用 户 组: 普通用户
  • 注册时间: 2011-09-30 18:17
文章分类

全部博文(28)

文章存档

2012年(1)

2011年(27)

我的朋友

分类: Python/Ruby

2011-12-11 21:02:16

  1. #!/usr/bin/perl
  2. use strict;
  3. use threads;
  4. use threads::shared;

  5. my $var=100;
  6. share($var); #### 共享变量进程和个线程之间

  7. my $t1 = threads -> create (\&thread_child, "T1");
  8. sleep 1;
  9. my $t2 = threads -> create (\&thread_child, "T2");

  10. print "do something in the main thread.......\n";
  11. sleep 1;
  12. &thread_child("main_thread");
  13. $t1 -> detach();
  14. $t2 -> detach();
  15. #print "T1 return the name is : $t1_res.....\n";

  16. #print "T2 return the name is : $t2_res.....\n";

  17. sub thread_child
  18. {
  19.    my @name =@_;
  20.    print "@name var is $var......\n";
  21.    $var ++;
  22.    
  23.  }

上锁共享变量

  1. #!/usr/bin/perl
  2. use strict;
  3. use threads;
  4. use threads::shared;
  5. use Thread::Semaphore;

  6. my $var=100;
  7. share($var);

  8. my $t1 = threads -> create (\&thread_child, "T1");

  9. my $t2 = threads -> create (\&thread_child, "T2");

  10. print "do something in the main thread.......\n";

  11. &thread_child("main_thread");
  12. $t1 -> detach();
  13. $t2 -> detach();

  14. sub thread_child
  15. {
  16.    my @name =@_;
  17.    {
  18.    lock ($var); ## 给var变量上锁,当块结束的时候,锁也就没有了
  19.    print "@name var is $var......\n";
  20.    $var ++;
  21.    }
  22.          
  23.  }

线程中的信号量,也就是PV操作

 

  1. #!/usr/bin/perl
  2. use strict;
  3. use threads;
  4. use threads::shared;
  5. use Thread::Semaphore; ## 线程信号量模块

  6. my $var=100;
  7. share($var);

  8. my $s = Thread:Semaphore->new();
  9. my $t1 = threads -> create (\&thread_child, "T1");

  10. my $t2 = threads -> create (\&thread_child, "T2");

  11. print "do something in the main thread.......\n";

  12. &thread_child("main_thread");
  13. $t1 -> detach();
  14. $t2 -> detach();

  15. sub thread_child
  16. {
  17.    my @name =@_;
  18.    $s->down(); P操作
  19.    print "@name var is $var......\n";
  20.    $var ++;
  21.    $s->up();      V操作
  22.  }

 

 

 

阅读(3644) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~