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

Python – 如何在同一时间等待队列和套接字

发布时间:2020-12-16 21:48:33 所属栏目:Python 来源:网络整理
导读:我想从Queue.Queue或TCP套接字中读取消息,以先到者为准. 如果不诉诸2个线程怎么能实现呢? 平台是Windows上的CPython 2.7.5 最佳答案 要在单个线程中执行此操作,您必须使用非阻塞方法,并将它们合并到单个事件循环中.我实际上在这里使用select而不是非阻塞套

我想从Queue.Queue或TCP套接字中读取消息,以先到者为准.
如果不诉诸2个线程怎么能实现呢?
平台是Windows上的CPython 2.7.5

最佳答案
要在单个线程中执行此操作,您必须使用非阻塞方法,并将它们合并到单个事件循环中.我实际上在这里使用select而不是非阻塞套接字I / O,因为如果你需要从多个套接字中读取它会稍微清晰…

import socket
import select
import Queue
import time

TIMEOUT = 0.1   # 100ms


def process_queue_item(item):
    print 'Got queue item: %r' % item


def process_socket_data(data):
    print 'Got socket data: %r' % data


def main():

    # Build queue
    queue = Queue.Queue()
    for i in range(10):
        queue.put(i)
    queue.put(None)   # Using None to indicate no more data on queue
    queue_active = True

    # Build socket
    sock = socket.socket()
    sock.connect(('www.google.com',80))
    sock.send('GET / HTTP/1.0rnrn')
    socket_active = True

    # Main event loop
    while 1:

        # If there's nothing to read,bail out
        if not (socket_active or queue_active):
            break

        # By default,sleep at the end of the loop
        do_sleep = True

        # Get data from socket without blocking if possible
        if socket_active:
            r,w,x = select.select([sock],[],TIMEOUT)
            if r:
                data = sock.recv(64)
                if not data:    # Hit EOF
                    socket_active = False
                else:
                    do_sleep = False
                    process_socket_data(data)

        # Get item from queue without blocking if possible
        if queue_active:
            try:
                item = queue.get_nowait()
                if item is None:  # Hit end of queue
                    queue_active = False
                else:
                    do_sleep = False
                    process_queue_item(item)
            except Queue.Empty:
                pass

        # If we didn't get anything on this loop,sleep for a bit so we
        # don't max out CPU time
        if do_sleep:
            time.sleep(TIMEOUT)


if __name__ == '__main__':
    main()

输出看起来像……

Got socket data: 'HTTP/1.0 302 FoundrnLocation: http://www.google.co.uk/rnCache-Co'
Got queue item: 0
Got socket data: 'ntrol: privaternContent-Type: text/html; charset=UTF-8rnSet-Cook'
Got queue item: 1
Got socket data: 'ie: PREF=ID=a192ab09b4c13176:FF=0:TM=1373055330:LM=1373055330:S='
Got queue item: 2
etc.

(编辑:李大同)

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

    推荐文章
      热点阅读