sathishperl has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I am facing problem when running multi-threaded program in CGI. I am sing apache 2.2 web server.

use CGI; use CGI::Carp qw(warningsToBrowser fatalsToBrowser); use strict; use warnings; use threads; my $cgi = new CGI; print $cgi->header(); print <<endhere; <html> <head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="Content-Type" content="text/html; charset=windows-12 +52"> </head> <body> endhere my $n= threads->create('new1')->detach(); sleep(1); my $m= threads->create('new2')->detach(); sleep(1); sub new1 { my $i=0; while(1) { print "IIIII $i <br>\n"; $i++; last if($i==25); sleep(1); } } sub new2 { my $i=0; while(1) { print "JJJJJ $i <br>\n"; $i++; last if($i==25); sleep(1); } } print <<endhere; </body> </html> endhere
Please let me know if I have missed anything in my code. Thanks, Sathish

Replies are listed 'Best First'.
Re: Perl CGI multithreading
by Anonymous Monk on Feb 22, 2011 at 07:17 UTC
    I am facing problem ...

    What problem are you facing?

    You'll likely get more useful replies if you don't expect people to have or install Apache 2.2 on a number of platforms and try it out for you.

Re: Perl CGI multithreading
by viveksnv (Sexton) on Feb 22, 2011 at 07:32 UTC
    Hi
    When using threads, I think we should consider three stages.. 1. create 2. Join 3. detach

    create - Creating a new thread
    join - Get the values from a already running thread
    detach - kill or terminate a running thread


    You may refer this tutorial before digging your program..i am going to read first... :)
    The following code is working for me.
    #!/usr/bin/perl use CGI; use CGI::Carp qw(warningsToBrowser fatalsToBrowser); use strict; use warnings; use threads; my $cgi = new CGI; print $cgi->header(); print <<"endhere"; <html> <head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="Content-Type" content="text/html; charset=windows-12 +52"> </head> <body> endhere my $n=threads->create(\&new1); my $m=threads->create(\&new2); sleep(1); my @data1 = $n->join; print @data1 . "\n"; my @data2 = $m->join; print @data2 . "\n"; #$n->detach; #$m->detach; sub new1 { my $i=0; while(1) { print "IIIII $i <br>\n"; $i++; last if($i==25); sleep(1); } } sub new2 { my $i=0; while(1) { print "JJJJJ $i <br>\n"; $i++; last if($i==25); sleep(1); } } print <<"endhere"; </body> </html> endhere


    Vivek