【问题标题】:How to share data between threads in this threaded TCPServer?如何在这个线程 TCPServer 中的线程之间共享数据?
【发布时间】:2013-04-09 07:05:13
【问题描述】:

我正在从事一个涉及通过 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()

所以这应该工作的方式是程序不断地打印 x 的值,并且随着新消息的进入 x 的值应该改变。似乎问题在于它在主线程中打印的 x 与在服务器线程中被分配新值的 x 不同。如何从我的服务器线程更改主线程中 x 的值?

【问题讨论】:

  • 你试过把print语句放到工作线程里吗?

标签: multithreading python-2.6 tcpserver


【解决方案1】:

尝试在您的线程之间共享Queue

有用的资源

【讨论】:

  • 谢谢,我知道我必须查看队列,但找不到好的资源。
  • 我链接到的演示文稿进入队列,给出了几个简短的例子。对这些概念的一般理解也很有帮助。
  • 对于那些在防火墙后面阻止 SlideShare 的人,这里是作者的页面:dabeaz.com/usenix2009/concurrent
  • 这个问题有一个很好的 MWE。所以有人应该使用这个 MWE 来提供答案,而不仅仅是链接到外部文档。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-01
  • 2015-09-08
  • 1970-01-01
  • 2012-03-19
  • 2023-03-25
相关资源
最近更新 更多