multithreading 如何在此线程 TCPServer 中的线程之间共享数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16044452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to share data between threads in this threaded TCPServer?
提问by David Lopez
I'm working on a project which involves sending data over TCP. Using the ThreadedTCPServer I'm able to do that already. The server thread only needs to read incoming strings of data and set the value of variables. Meanwhile I need the main thread to see those variables changing value. Here's my code so far, just modified from the ThreadedTCPServer example:
我正在从事一个涉及通过 TCP 发送数据的项目。使用 ThreadedTCPServer 我已经能够做到这一点。服务器线程只需要读取传入的数据字符串并设置变量的值。同时我需要主线程来查看这些变量的值变化。到目前为止,这是我的代码,刚刚从 ThreadedTCPServer 示例中修改:
import socket
import threading
import SocketServer
x =0
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(1024)
# a few lines of code in order to decipher the string of data incoming
x = 0, 1, 2, etc.. #depending on the data string it just received
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = 192.168.1.50, 5000
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
print "Server loop running in thread:", server_thread.name
while True:
print x
time.sleep(1)
server.shutdown()
So the way this should work is that the program constantly prints the value of x, and as new messages come in the value of x should change. It seems the problem is that the x that it prints in the main thread is not the same x which is being assigned a new value in the server threads. How can I change the value of x in the main thread from my server thread?
所以这应该工作的方式是程序不断打印 x 的值,并且随着新消息的传入 x 的值应该改变。似乎问题在于它在主线程中打印的 x 与在服务器线程中被分配新值的 x 不同。如何从服务器线程更改主线程中 x 的值?
回答by Anton Strogonoff
Try sharing a Queue
between your threads.
尝试Queue
在您的线程之间共享一个。
Useful resources
有用的资源
- An Introduction to Python Concurrency, a presentation by David Beazley, provides a good nice intro to multithreading, thread communication, and concurrency in general.
- An Introduction to Python Concurrency是 David Beazley 的演讲,提供了对多线程、线程通信和一般并发的很好的介绍。