我正在尝试理解python中的基本线程,我无法理解池如何与队列模块一起工作。下面是我正在阅读的方法中使用的示例服务器:http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/2/。基本上我不明白的是变量pickledList如何最终可用于线程范围被发送到客户端,因为它从未传递到代码中的任何位置的线程
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() )
答案 0 :(得分:4)
pickledList
变量可用作ClientThread
类中的全局变量。请参阅Short Description of Python Scoping Rules。
答案 1 :(得分:-2)
线程没有自己的命名空间。 pickledList
被定义为全局,因此对象可以访问它。从技术上讲,它应该在函数的顶部有一个global pickledList
来清除它,但并不总是需要它。
修改强>
明确表示,我的意思是“明确人。”