Port eg/threaded.pl to ithreads
[catagits/fcgi2.git] / perl / eg / threaded.pl
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4 use threads;
5 use threads::shared;
6
7 use FCGI       qw[];
8 use IO::Handle qw[];
9
10 use constant THREAD_COUNT => 5;
11
12 my @count : shared = (0, (0) x THREAD_COUNT);
13
14 sub worker {
15     my $k = shift;
16     my %env;
17     my $in  = IO::Handle->new;
18     my $out = IO::Handle->new;
19     my $err = IO::Handle->new;
20
21     my $request = FCGI::Request($in, $out, $err, \%env);
22
23     while ($request->Accept >= 0) {
24         print $out
25                "Content-type: text/html\r\n",
26                "\r\n",
27                "<title>FastCGI Hello! (multi-threaded perl, fcgiapp library)</title>",
28                "<h1>FastCGI Hello! (multi-threaded perl, fcgiapp library)</h1>",
29                "Request counts for ", THREAD_COUNT ," threads ",
30                "running on host <i>$env{SERVER_NAME}</i>";
31
32         {
33             lock(@count);
34
35             ++$count[$k];
36
37             for(my $i = 1; $i <= THREAD_COUNT; $i++) {
38                 print $out $count[$i];
39                 print $out " ";
40             }
41         }
42         $request->Flush;
43         sleep(1);
44     }
45 }
46
47 $_->join for map { threads->create(\&worker, $_) } 1..THREAD_COUNT;
48