从对象的方法创建线程

时间:2016-06-22 15:12:06

标签: python multithreading python-2.7

如何在一个显示here的示例中使一个线程运行TCP服务器实例的循环函数。

tcpserver.py     import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever() # <== make a thread for serve_forever()

我尝试添加以下代码并在一个线程中运行 server_forever(),但执行没有克服它的调用。

 from threading import Thread, Lock
 server_thread = Thread(target=server.serve_forever())
 server_thread.start()
 print "Execution doesn't get to this point"

如何启动 server_forever()以便我可以在调用后运行代码?

即使从远程python模块调用包含服务器的文件,执行服务器运行时执行仍会挂起,这也有点奇怪。例如,运行:

import os

os.system("python /path/to/tcpserver.py")
print "Execution doesn't get here either"

产生相同的结果。

建议的重复问题的答案中的代码不适用于上述示例。

0 个答案:

没有答案