加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

多线程 – 如何在这个线程TCPServer中的线程之间共享数据?

发布时间:2020-12-15 07:38:01 所属栏目:Java 来源:网络整理
导读:我正在开发一个涉及通过TCP发送数据的项目.使用ThreadedTCPServer我已经能够做到这一点.服务器线程只需要读取传入的数据字符串并设置变量的值.同时我需要主线程来查看那些变量值的变量.到目前为止,这是我的代码,只是从ThreadedTCPServer示例修改: import so
我正在开发一个涉及通过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值?

解决方法

尝试在线程之间共享 Queue.

有用的资源

> An Introduction to Python Concurrency,David Beazley的演讲,提供了一个很好的介绍多线程,线程通信和一般的并发性.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读