Global variables in mod_perl

G

Gunnar Hjalmarsson

If I run this script:

$count++;
print "Content-type: text/plain\n\n";
print $count;

20 times under mod_perl, it outputs:

1 1 1 1 2 1 1 1 2 2 1 3 2 1 3 2 2 3 4 4

while I would have expected it to output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

System:
Linux Fedora Core 1
Apache 2.0.47
mod_perl 1.99_12
perl v5.8.1

Anybody who has an idea of what I'm missing?
 
M

Mark Clements

Gunnar said:
If I run this script:

$count++;
print "Content-type: text/plain\n\n";
print $count;

20 times under mod_perl, it outputs:

1 1 1 1 2 1 1 1 2 2 1 3 2 1 3 2 2 3 4 4

while I would have expected it to output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
apache is traditionally multiprocessed - there is no guarantee that a
second or subsequent request will be served by the same child. Try

print "$$ $count\n";

Mark
 
G

Gunnar Hjalmarsson

Mark said:
apache is traditionally multiprocessed - there is no guarantee that
a second or subsequent request will be served by the same child.
Try

print "$$ $count\n";

Aha, thanks!

As an exercise, just to convince myself, I put together the following
code:

use SDBM_File;
use Fcntl;
print "Content-type: text/plain\n\n";
my $file = '/path/to/file';
my $total;

$count ++;

tie my %counts, 'SDBM_File', $file, O_RDWR|O_CREAT, 0644;
$counts{$$} = $count;
for (sort keys %counts) {
print "$_: $counts{$_}\n";
$total += $counts{$_};
}
untie %counts;

print "\nTotal: $total\n";

Now the result is as expected:

10569: 2
10570: 3
10571: 2
10572: 2
10573: 3
10574: 2
10575: 4
10576: 2

Total: 20

Previously I have only played with mod_perl using my IndigoPerl
installation on Windows 98, which (I suppose) runs as one single process.
 
J

Joe Smith

Gunnar said:
Hmm.. Mark convinced me that it was caused by multiple processes rather
than threads. Can you please explain?

Some operating systems implement threads in a way that they look like
processes. The value $$ is different in each thread.
-Joe
 
G

Gunnar Hjalmarsson

Joe said:
Some operating systems implement threads in a way that they look
like processes. The value $$ is different in each thread.

Okay, thanks. Guess I need to read up on both processes and threads...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top