[mod_python] Shared global variables among apache children?

Joshua Ginsberg listspam at flowtheory.net
Thu Aug 10 15:25:36 EDT 2006

Geez, there are a lot of questions about IPC this week... :-/

Justin --

Let's say you open two terminals, and in each you run a python
interpreter. In the first, you tell it:

>>> x = 3

And in the second you tell it:

>>> x = 3

And then back in the first you tell it:

>>> x += 1

And then in the second you tell it:

>>> print x

What are you going to get? 3 of course -- not 4. Duh! That's because
they're separate processes. Separate memory spaces. Totally independent.
It's the same thing with Apache. Each Apache process runs with its own
unique memory space and its own unique Python instance.

So solve this problem the same way you'd solve it with two separate
Python interpreter processes. Examples:

1) Use files and locks.
2) Use something like SQL that has locking built in.
3) Use some IPC protocol -- XMLRPC or (hehe) D-BUS

But if you want a purely multithreaded web server that has one big
shared memory space, use AOLServer or something like that. Apache was
originally designed to do forking and lots of it. It's only recently
that it has been developing MPM models that have multiple connections
handled by a process with multiple threads, and this doesn't happen the
same way in all MPMs or on all platforms.


On Thu, 2006-08-10 at 14:08 -0500, justind wrote:
> It feels like I'm missing either one configuration option or this may 
> not even be possible.
> I have this little bit of code. I expected, that every 4 seconds that x 
> would increment by 1 on the returned page. It does. However I think that 
> this same code is loaded into each child process (correct me if I'm 
> wrong) of apache.
> Depending on which child I get, and when they were launched (hitting 
> refresh rapidly on Firefox seems to demonstrate this too me) I get a 
> different page back. One will show 4 then a refresh will show 3, another 
> will show 3, another will show 4 and so on and so forth.
> I guess my question is, how can I share the global variable of x among 
> all the apache child processes, or is this really my problem)?
> Any help would be very appreciated.
> Code follows below:
> from mod_python import apache
> import time
> import thread
> x = 1
> def handler(req):
>     global x
>     req.content_type = 'text/plain'
>     req.write("Hello World! " + str(x))
>     return apache.OK
> def do_me():
>     global x
>     while True:
>         time.sleep(4)
>         x += 1               
> thread.start_new(do_me,())   
> _______________________________________________
> Mod_python mailing list
> Mod_python at modpython.org
> http://mailman.modpython.org/mailman/listinfo/mod_python

More information about the Mod_python mailing list