2009-08-04 45 views
2

我想了解python中的基本线程,我无法理解pooling如何与队列模块一起工作。下面是我使用的示例服务器示例服务器:http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/2/。基本上我不明白的是变量pickledList如何最终提供给线程范围,因为它永远不会传递给线程的代码的任何地方被运出到客户端有人可以帮助我理解这个简短的.py

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()) 

回答

-2

线程没有自己的命名空间。 pickledList被定义为全局的,所以它可以被对象访问。从技术上讲,它应该在函数的顶部有一个global pickledList来明确,但并不总是需要。

编辑

通过讲清楚,我的意思是 “讲清楚一个人的。”

+0

如果在清单中声明了类后声明了pickledList,它会以相同的方式工作吗? – Ryan 2009-08-04 13:48:11

相关问题