What you want is threads. Here are an example of how to do this. Note, this script is only for Perl-5.8.0, don't use other version. I recommend that you compile Perl-5.8.0 without PerlIO, because if you are using sockets with PerlIO you will get a lot of bugs! PerlIO is very good, but now it has some bugs to solve (see the perlbug list), we need to wait for Perl-5.8.1 or get the last pathches.
This example show how to use the share resource of threads. If you want a variable that can be shared by the other threads, just declare it like the example, with : share in the end, don't forget to load the module threads::shared!
Other thing, note that the main is another thread too! If it goes out (exit), the other threads will be closed too. To wait a thread use the command join: $thread->join
#!/usr/bin/perl
use threads;
use threads::shared;
$|=1;
my ($global) : shared ;
my $thr1 = threads->new(\&TEST,1) ;
my $thr2 = threads->new(\&TEST,2) ;
my @ReturnData = $thr1->join ;
print "Thread 1 returned: @ReturnData\n" ;
my @ReturnData = $thr2->join ;
print "Thread 2 returned: @ReturnData\n" ;
########
# TEST #
########
sub TEST {
my ( $id ) = @_ ;
for(0..10) {
$global++ ;
print "id: $id >> $_ >> GLB: $global\n" ;
sleep(1) ;
}
return( $id ) ;
}
Graciliano M. P.
"The creativity is the expression of the liberty".
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.