views:

185

answers:

2

I'm trying to understand basic threading in python, I'm having trouble understanding how pooling works with the queue module. Heres the example server used in the howto I'm reading from: http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/2/. Basically what I don't understand is how the variable pickledList ends up available to the threads scope to be shipped out to the client since its never passed to the thread anywhere in the code

import pickle
import Queue
import socket
import threading

# We'll pickle a list of numbers, yet again:
someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( someList )

# A revised version of our thread class:
class ClientThread ( threading.Thread ):

   # Note that we do not override Thread's __init__ method.
   # The Queue module makes this not necessary.

   def run ( self ):

      # Have our thread serve "forever":
      while True:

         # Get a client out of the queue
         client = clientPool.get()

         # Check if we actually have an actual client in the client variable:
         if client != None:

            print 'Received connection:', client [ 1 ] [ 0 ]
            client [ 0 ].send ( pickledList )
            for x in xrange ( 10 ):
               print client [ 0 ].recv ( 1024 )
            client [ 0 ].close()
            print 'Closed connection:', client [ 1 ] [ 0 ]

# Create our Queue:
clientPool = Queue.Queue ( 0 )

# Start two threads:
for x in xrange ( 2 ):
   ClientThread().start()

# Set up the server:
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )

# Have the server serve "forever":
while True:
   clientPool.put ( server.accept() )
+4  A: 

The pickledList variable is available as a global variable in the ClientThread class. See Short Description of Python Scoping Rules.

Ville Laurikari
A: 

Threads don't have their own namespace. pickledList is defined as a global, so it is accessible to the object. Technically it should have had a global pickledList at the top of the function to make that clear, but it's not always needed.

EDIT

By make it clear, I mean "make it clear to a human."

Christopher
Would it work the same way if pickledList was declared after the class was declared in the listing?
Ryan
Sorry Christopher, what you're saying about the "global" is unfortunately wrong. The module-level, global scope is part of the regular lookup chain in Python, with no need of using the global keyword. You have to use the global keyword only if you want to "rebind" the variable to a new object, i.e., if you want to use the assignement statement on it.
krawyoti
@krawyoti: Note that I said "to make it clear". I know that it's not syntactically necessary.
Christopher