如何在此线程化的TCPServer中的线程之间共享数据? [英] How to share data between threads in this threaded TCPServer?

查看:136
本文介绍了如何在此线程化的TCPServer中的线程之间共享数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事一个涉及通过TCP发送数据的项目.使用ThreadedTCPServer,我已经可以做到这一点.服务器线程仅需要读取传入的数据字符串并设置变量的值.同时,我需要主线程来查看那些变量的值更改.到目前为止,这是我的代码,只是从ThreadedTCPServer示例中进行了修改:

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:

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值?

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?

推荐答案

尝试共享 Queue 在线程之间.

Try sharing a Queue between your threads.

    David Beazley的演示
  • Python并发简介提供了一个很好的全面介绍多线程,线程通信和并发性.
  • An Introduction to Python Concurrency, a presentation by David Beazley, provides a good nice intro to multithreading, thread communication, and concurrency in general.

这篇关于如何在此线程化的TCPServer中的线程之间共享数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆