+ -
当前位置:首页 → 问答吧 → 子线程中执行sleep(5),主线程也跟着sleep?

子线程中执行sleep(5),主线程也跟着sleep?

时间:2011-07-17

来源:互联网

本帖最后由 heidern 于 2011-07-17 15:20 编辑

最近在研究多线程,想写个服务器端程序.
  1. #!/usr/local/perl5.12/bin/perl
  2. use strict;
  3. use warnings;
  4. use threads (
  5.         'exit' => 'threads_only',
  6. );
  7. use IO::Socket;
  8. use Data::Dumper;

  9. $|=1;
  10. my $serverFD=IO::Socket::INET->new(
  11.         LocalPort       =>      12340,
  12.         Type            =>      SOCK_STREAM,
  13.         Listen          =>      SOMAXCONN,
  14.         Reuse           =>      1
  15. ) || die $!;

  16. # create a thread to monitor the threads
  17. threads->create(\&threadMonitor);

  18. # when a connect accepted , create a thread to process it
  19. while (1) {
  20.         threads->create(\&talk,$serverFD->accept());
  21. }

  22. sub talk
  23. {
  24.         my ($clientFD,$clientInfo)=@_;
  25.         my ($clientport,$clientaddr) = unpack_sockaddr_in($clientInfo);
  26.         my $clientip = inet_ntoa($clientaddr);
  27.         my $tid = threads->self->tid();
  28.         print "Client From => $clientip\:$clientport My number is $tid\n";
  29.         while (<$clientFD>) {
  30.                 print "client $tid from $clientip say: $_";
  31.                 chomp($_);
  32.                 if ($_ =~ m/hello/i) {
  33.                         print $clientFD "tid=$tid,Hello Client from $clientip\n";
  34.                 } elsif ($_ =~ m/bye/i) {
  35.                         print $clientFD "tid=$tid,Bye Bye Client from $clientip\n";
  36.                         close $clientFD;
  37.                         last;
  38.                 }
  39.         }
  40.         threads->self->detach();
  41. }

  42. sub threadMonitor
  43. {
  44.         print "Monitor Thread Created!!\n";
  45.         while(1) {
  46.                 my @ths_r=threads->list(threads::running);
  47.                 my $threadNums_running=$#ths_r+1;
  48.                 my @ths_j=threads->list(threads::joinable);
  49.                 my $threadNums_joinable=$#ths_j+1;
  50.                 print "There are $threadNums_running threads running and $threadNums_joinable threads joinable\n";
  51.                 sleep(5);
  52.         }
  53.         threads->self->detach();
  54. }
复制代码
当threadMonitor这个线程sleep的时候,主线程也会sleep,为什么?

作者: heidern   发布时间: 2011-07-17

怎么就都这么迷信多线程呢。

作者: flw   发布时间: 2011-07-17