【发布时间】:2019-03-24 20:00:11
【问题描述】:
我找不到唯一标识在服务器上创建和保存的每个线程的方法。每个客户端线程都必须存储自己的信息,这些信息用于将信息中继回其各自的客户端。省略了服务器创建的明显细节:
import sys
from threading import Thread
import socket
import traceback
def client_thread(conn, ip, port, MAX_BUFFER_SIZE = 4096):
while 1:
# the input is in bytes, so decode it
input_from_client_bytes = conn.recv(MAX_BUFFER_SIZE)
if not input_from_client_bytes:
break
# decode input and strip the end of line
input_from_client = input_from_client_bytes.decode("utf8").rstrip()
aString = ''
if (input_from_client.startswith('LOAD BOARD')):
array = input_from_client.split('~')
aString = array[1]
vysl = aString.encode("utf8") # encode the result string
conn.sendall(vysl) # send it to client
conn.close() # close connection
print('Connection ' + ip + ':' + port + " ended")
while True:
conn, addr = soc.accept()
ip, port = str(addr[0]), str(addr[1])
print('Accepting connection from ' + ip + ':' + port)
try:
Thread(target=client_thread, args=(conn, ip, port)).start()
except:
traceback.print_exc()
soc.close()
start_server()
我读到的一个建议是创建一个 python 文件并在其中添加所有变量并将其导入服务器,但是所有其他线程同时编辑这些值,事情会变得很奇怪。每个线程都希望使用服务器将提供的方法。由于无法在一个类的方法和另一个类的方法之间交换数据,那么最好的方法是什么?
【问题讨论】:
-
我开始回答,但后来意识到,你打算如何使用线程ID?
-
您始终可以使用
thread.get_ident()(Python 3.3+:threading.get_ident())识别当前线程,然后使用 ID 作为共享字典中的键,以确保您正在访问仅限当前线程。
标签: python multithreading identify