gpt4 book ai didi

python - 有人可以帮我理解这个简短的 .py

转载 作者:行者123 更新时间:2023-12-03 13:01:36 25 4
gpt4 key购买 nike

我试图理解 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() )

最佳答案

pickledList变量可用作 ClientThread 中的全局变量类(class)。见 Short Description of Python Scoping Rules .

关于python - 有人可以帮我理解这个简短的 .py,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1227448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com