具有多个线程的Python脚本通常只在debug mod中工作

2024-09-26 18:03:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用一个python2.7脚本和多个线程。其中一个线程正在长轮询模式下监听JSON数据,并在接收到数据后进行解析,或者在一段时间后进入超时状态。我注意到它只在调试模式下工作(我使用Wing IDE)。在正常运行的情况下,脚本的这个特定线程似乎在第一次GET请求之后,在进入“for”循环之前挂起。循环条件不影响结果。同时,其他线程继续正常工作。在

我认为这与多线程有关。如何正确排除和修复此问题?在

下面我把负责长时间轮询工作的类代码。在

class Listener(threading.Thread):

def __init__(self, router, *args, **kwargs):
    self.stop = False

    self._cid = kwargs.pop("cid", None)
    self._auth = kwargs.pop("auth", None)
    self._router = router
    self._c = webclient.AAHWebClient()

    threading.Thread.__init__(self, *args, **kwargs)

def run(self):
    while True:
        try:
            # Data items that should be routed to the device is retrieved by doing a 
            # long polling GET request on the "/tunnel" resource. This will block until
            # there are data items available, or the request times out
            log.info("LISTENER: Waiting for data...")

            response = self._c.send_request("GET", self._cid, auth=self._auth)

            # A timed out request will not contain any data             
            if len(response) == 0:
                log.info("LISTENER: No data this time")             
            else:
                items = response["resources"]["tunnel"]
                undeliverable = []

                #print items # - reaching this point, able to return output

                for item in items:

                    # The data items contains the data as a base64 encoded string and the 
                    # external reference ID for the device that should receive it
                    extId = item["extId"]
                    data = base64.b64decode(item["data"])

                    # Try to deliver the data to the device identified by "extId"
                    if not self._router.route(extId, data):
                        item["message"] = "Could not be routed"
                        undeliverable.append(item)

                # Data items that for some reason could not be delivered to the device should
                # be POST:ed back to the "/tunnel" resource as "undeliverable"
                if len(undeliverable) > 0:
                    log.warning("LISTENER: Sending error report...")
                    response = self._c.send_request("POST", "/tunnel", body={"undeliverable": undeliverable}, auth=self._auth)

            except webclient.RequestError as e:
                log.error("LISTENER: ERROR %d - %s", e.status, e.response)

升级版:

^{pr2}$

Tags: thetoselfauthfordataresponserequest
1条回答
网友
1楼 · 发布于 2024-09-26 18:03:15

如果您使用的是CPython解释器you're not actually system threading

CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.

因此,您的进程可能在侦听第一个请求时锁定,因为您的轮询时间很长。在

多处理可能是更好的选择。我没有尝试过长时间轮询,但是the Twisted framework可能也适用于您的情况。在

相关问题 更多 >

    热门问题