Shabareesh
Shabareesh

Reputation: 331

Python thread blocking further execution

I have been trying to write a python script that initiates a thread to listen on a socket and send HTTP data to another application to be launched by the same program. There is a requirement for the socket server to be running prior to executing the application. However, the thread running the socket server blocks further execution of the program and it freezes where it is listening. Putting some dummy code.

In module 1:

def runServer(Port, Host, q):
    HTTPServerObj = HTTPServer((Host, Port), RequestHandler)
    HTTPServerObj.handle_request()
    HTTPServerObj.server_close()
    q.put((True, {'messageDoNotDuplicate': 'Data sent successfully by the server'}))

class SpoofHTTPServer(object):
    def runServerThread(self):
        q = Queue.Queue()
        serverThread=Thread(target=runServer, args=(self.Port, self.Host, q))
        serverThread.daemon=True
        serverThread.start()
        result = q.get()
        print result
        return result

In module 2:

from module1 import SpoofHTTPServer

spoofHTTPServer = SpoofHTTPServer()
result = spoofHTTPServer.runServerThread()
rc = myApp.start()

The myApp.start() never gets executed as the thread is blocking it.

Upvotes: 1

Views: 282

Answers (2)

Noctis Skytower
Noctis Skytower

Reputation: 22041

This may work for you from Python 3. Make a connection to ('localhost', 8080) to see it work.

import queue as Queue
from threading import Thread
from http.server import HTTPServer
from socketserver import BaseRequestHandler as RequestHandler

def runServer(Port, Host, q):
    HTTPServerObj = HTTPServer((Host, Port), RequestHandler)
    HTTPServerObj.handle_request()
    HTTPServerObj.server_close()
    q.put((True, {'messageDoNotDuplicate':
                  'Data sent successfully by the server'}))

class SpoofHTTPServer(object):

    Port = 8080
    Host = ''

    def runServerThread(self):
        q = Queue.Queue()
        serverThread=Thread(target=runServer, args=(self.Port, self.Host, q))
        serverThread.daemon=True
        serverThread.start()
        result = q.get()
        print(result)
        return result

spoofHTTPServer = SpoofHTTPServer()
result = spoofHTTPServer.runServerThread()
##rc = myApp.start()

Upvotes: 0

Kaivosukeltaja
Kaivosukeltaja

Reputation: 15735

It looks to me like the method that blocks execution is not the thread but q.get(). It will listen to the Queue until an item is available, but since it's executed before running the client application nothing ever gets posted into the queue. Maybe you should return q instead and listen to the queue in module 2 after calling myApp.start()?

Upvotes: 1

Related Questions