第十一章:Python の 网络编程基础(三)

本課主題

  • 多线程的创建和使用
  • 消息队列的介绍
  • Python 操作 memached 和 redis 实战
  • 本周作业

消息队列的介绍

对列是在内存中创建的,如果程序运行完毕之后被清空了,消息就清空了。

先进先出队列

class Queue:
    ‘‘‘Create a queue object with a given maximum size.

    If maxsize is <= 0, the queue size is infinite.
    ‘‘‘

    def __init__(self, maxsize=0):
        self.maxsize = maxsize
        self._init(maxsize)

        # mutex must be held whenever the queue is mutating.  All methods
        # that acquire mutex must release it before returning.  mutex
        # is shared between the three conditions, so acquiring and
        # releasing the conditions also acquires and releases mutex.
        self.mutex = threading.Lock()

        # Notify not_empty whenever an item is added to the queue; a
        # thread waiting to get is notified then.
        self.not_empty = threading.Condition(self.mutex)

        # Notify not_full whenever an item is removed from the queue;
        # a thread waiting to put is notified then.
        self.not_full = threading.Condition(self.mutex)

        # Notify all_tasks_done whenever the number of unfinished tasks
        # drops to zero; thread waiting to join() is notified to resume
        self.all_tasks_done = threading.Condition(self.mutex)
        self.unfinished_tasks = 0

    def task_done(self):
        ‘‘‘Indicate that a formerly enqueued task is complete.

        Used by Queue consumer threads.  For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items
        have been processed (meaning that a task_done() call was received
        for every item that had been put() into the queue).

        Raises a ValueError if called more times than there were items
        placed in the queue.
        ‘‘‘
        with self.all_tasks_done:
            unfinished = self.unfinished_tasks - 1
            if unfinished <= 0:
                if unfinished < 0:
                    raise ValueError(‘task_done() called too many times‘)
                self.all_tasks_done.notify_all()
            self.unfinished_tasks = unfinished

    def join(self):
        ‘‘‘Blocks until all items in the Queue have been gotten and processed.

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer thread calls task_done()
        to indicate the item was retrieved and all work on it is complete.

        When the count of unfinished tasks drops to zero, join() unblocks.
        ‘‘‘
        with self.all_tasks_done:
            while self.unfinished_tasks:
                self.all_tasks_done.wait()

    def qsize(self):
        ‘‘‘Return the approximate size of the queue (not reliable!).‘‘‘
        with self.mutex:
            return self._qsize()

    def empty(self):
        ‘‘‘Return True if the queue is empty, False otherwise (not reliable!).

        This method is likely to be removed at some point.  Use qsize() == 0
        as a direct substitute, but be aware that either approach risks a race
        condition where a queue can grow before the result of empty() or
        qsize() can be used.

        To create code that needs to wait for all queued tasks to be
        completed, the preferred technique is to use the join() method.
        ‘‘‘
        with self.mutex:
            return not self._qsize()

    def full(self):
        ‘‘‘Return True if the queue is full, False otherwise (not reliable!).

        This method is likely to be removed at some point.  Use qsize() >= n
        as a direct substitute, but be aware that either approach risks a race
        condition where a queue can shrink before the result of full() or
        qsize() can be used.
        ‘‘‘
        with self.mutex:
            return 0 < self.maxsize <= self._qsize()

    def put(self, item, block=True, timeout=None):
        ‘‘‘Put an item into the queue.

        If optional args ‘block‘ is true and ‘timeout‘ is None (the default),
        block if necessary until a free slot is available. If ‘timeout‘ is
        a non-negative number, it blocks at most ‘timeout‘ seconds and raises
        the Full exception if no free slot was available within that time.
        Otherwise (‘block‘ is false), put an item on the queue if a free slot
        is immediately available, else raise the Full exception (‘timeout‘
        is ignored in that case).
        ‘‘‘
        with self.not_full:
            if self.maxsize > 0:
                if not block:
                    if self._qsize() >= self.maxsize:
                        raise Full
                elif timeout is None:
                    while self._qsize() >= self.maxsize:
                        self.not_full.wait()
                elif timeout < 0:
                    raise ValueError("‘timeout‘ must be a non-negative number")
                else:
                    endtime = time() + timeout
                    while self._qsize() >= self.maxsize:
                        remaining = endtime - time()
                        if remaining <= 0.0:
                            raise Full
                        self.not_full.wait(remaining)
            self._put(item)
            self.unfinished_tasks += 1
            self.not_empty.notify()

    def get(self, block=True, timeout=None):
        ‘‘‘Remove and return an item from the queue.

        If optional args ‘block‘ is true and ‘timeout‘ is None (the default),
        block if necessary until an item is available. If ‘timeout‘ is
        a non-negative number, it blocks at most ‘timeout‘ seconds and raises
        the Empty exception if no item was available within that time.
        Otherwise (‘block‘ is false), return an item if one is immediately
        available, else raise the Empty exception (‘timeout‘ is ignored
        in that case).
        ‘‘‘
        with self.not_empty:
            if not block:
                if not self._qsize():
                    raise Empty
            elif timeout is None:
                while not self._qsize():
                    self.not_empty.wait()
            elif timeout < 0:
                raise ValueError("‘timeout‘ must be a non-negative number")
            else:
                endtime = time() + timeout
                while not self._qsize():
                    remaining = endtime - time()
                    if remaining <= 0.0:
                        raise Empty
                    self.not_empty.wait(remaining)
            item = self._get()
            self.not_full.notify()
            return item

    def put_nowait(self, item):
        ‘‘‘Put an item into the queue without blocking.

        Only enqueue the item if a free slot is immediately available.
        Otherwise raise the Full exception.
        ‘‘‘
        return self.put(item, block=False)

    def get_nowait(self):
        ‘‘‘Remove and return an item from the queue without blocking.

        Only get an item if one is immediately available. Otherwise
        raise the Empty exception.
        ‘‘‘
        return self.get(block=False)

    # Override these methods to implement other queue organizations
    # (e.g. stack or priority queue).
    # These will only be called with appropriate locks held

    # Initialize the queue representation
    def _init(self, maxsize):
        self.queue = deque()

    def _qsize(self):
        return len(self.queue)

    # Put a new item in the queue
    def _put(self, item):
        self.queue.append(item)

    # Get an item from the queue
    def _get(self):
        return self.queue.popleft()

class Queue源码

后进先出队列

class LifoQueue(Queue):
    ‘‘‘Variant of Queue that retrieves most recently added entries first.‘‘‘

    def _init(self, maxsize):
        self.queue = []

    def _qsize(self):
        return len(self.queue)

    def _put(self, item):
        self.queue.append(item)

    def _get(self):
        return self.queue.pop()

class LifoQueue源码

优先级先出对列 Priority Queue

class PriorityQueue(Queue):
    ‘‘‘Variant of Queue that retrieves open entries in priority order (lowest first).

    Entries are typically tuples of the form:  (priority number, data).
    ‘‘‘

    def _init(self, maxsize):
        self.queue = []

    def _qsize(self):
        return len(self.queue)

    def _put(self, item):
        heappush(self.queue, item)

    def _get(self):
        return heappop(self.queue)

class PriorityQueue源码

双向对列

class deque(object):
    """
    deque([iterable[, maxlen]]) --> deque object

    A list-like sequence optimized for data accesses near its endpoints.
    """
    def append(self, *args, **kwargs): # real signature unknown
        """ Add an element to the right side of the deque. """
        pass

    def appendleft(self, *args, **kwargs): # real signature unknown
        """ Add an element to the left side of the deque. """
        pass

    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from the deque. """
        pass

    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a deque. """
        pass

    def count(self, value): # real signature unknown; restored from __doc__
        """ D.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, *args, **kwargs): # real signature unknown
        """ Extend the right side of the deque with elements from the iterable """
        pass

    def extendleft(self, *args, **kwargs): # real signature unknown
        """ Extend the left side of the deque with elements from the iterable """
        pass

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        D.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ D.insert(index, object) -- insert object before index """
        pass

    def pop(self, *args, **kwargs): # real signature unknown
        """ Remove and return the rightmost element. """
        pass

    def popleft(self, *args, **kwargs): # real signature unknown
        """ Remove and return the leftmost element. """
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """ D.remove(value) -- remove first occurrence of value. """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ D.reverse() -- reverse *IN PLACE* """
        pass

    def rotate(self, *args, **kwargs): # real signature unknown
        """ Rotate the deque n steps to the right (default n=1).  If n is negative, rotates left. """
        pass

    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass

    def __bool__(self, *args, **kwargs): # real signature unknown
        """ self != 0 """
        pass

    def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self. """
        pass

    def __copy__(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a deque. """
        pass

    def __delitem__(self, *args, **kwargs): # real signature unknown
        """ Delete self[key]. """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, *args, **kwargs): # real signature unknown
        """ Return self[key]. """
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __iadd__(self, *args, **kwargs): # real signature unknown
        """ Implement self+=value. """
        pass

    def __imul__(self, *args, **kwargs): # real signature unknown
        """ Implement self*=value. """
        pass

    def __init__(self, iterable=(), maxlen=None): # known case of _collections.deque.__init__
        """
        deque([iterable[, maxlen]]) --> deque object

        A list-like sequence optimized for data accesses near its endpoints.
        # (copied from class doc)
        """
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value.n """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __reversed__(self): # real signature unknown; restored from __doc__
        """ D.__reversed__() -- return a reverse iterator over the deque """
        pass

    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass

    def __setitem__(self, *args, **kwargs): # real signature unknown
        """ Set self[key] to value. """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -- size of D in memory, in bytes """
        pass

    maxlen = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """maximum size of a deque or None if unbounded"""

    __hash__ = None

class deque源码

消息队列的好处

处理并发的能力变大啦

Python 操作 memached 和 redis 实战

本周作业

參考資料

银角大王:

金角大王:

时间: 2024-10-07 19:15:24

第十一章:Python の 网络编程基础(三)的相关文章

python网络编程基础(线程与进程、并行与并发、同步与异步)

python网络编程基础(线程与进程.并行与并发.同步与异步) 目录 线程与进程 并行与并发 同步与异步 线程与进程 进程 前言 进程的出现是为了更好的利用CPU资源使到并发成为可能. 假设有两个任务A和B,当A遇到IO操作,CPU默默的等待任务A读取完操作再去执行任务B,这样无疑是对CPU资源的极大的浪费.聪明的老大们就在想若在任务A读取数据时,让任务B执行,当任务A读取完数据后,再切换到任务A执行.注意关键字切换,自然是切换,那么这就涉及到了状态的保存,状态的恢复,加上任务A与任务B所需要的

PYTHON网络编程基础 pdf扫描版高清下载

PYTHON网络编程基础 pdf,本书全面介绍了使用PYTHON进行网络编程的基础知识,高级网络操作.WebServices.解析HTML和XHTML.XML.FTP.使用PYTHON操作数据库.SSL.几种服务器端框架,以及多任务处理等,实用性比较强,书中提供了175个实例,6600行以上的代码. 目录 第1部分 底层网络 第1章 客户/服务器网络介绍 第2章 网络客户端 第3章 网络服务器 第4章 域名系统 第5章 域名系统 第2部分 Web Service 第6章 Web客户端访问 第7章

Python网络编程基础笔记

第一部分:底层网络 第一章:客户/服务器网络介绍 1.1 理解TCP基础 TCP/IP事实上是一些协议的合集.当前大多数使用中的通信都使用TCP协议. 为了实现共享,TCP是通过把您要发送的数据流分解成很多小信息包在Internet上传输的(也许还伴有其他程序的信息包),而这些信息包到了接收者的地方会再次重新合成在一起. Internet连接就会用很少的时间来发送数据的每一个比特(bit),而其他程序的信息包也可以同时被传送. 1.1.1 寻址 第二章:网络客户端 第三章:网络服务器 第四章:域

《Python网络编程基础》笔记

主要是关于<Python网络编程笔记>这本书的笔记...可能有点乱... 总共包含6个部分.. 第一部分 第1章:客户/服务器网络介绍 未完待续.....

《Python网络编程基础》第四章 域名系统

域名系统(DNS) 是一个分布式的数据库,它主要用来把主机名转换成IP地址.DNS以及相关系统之所以存在,主要有以下两个原因: 它们可以使人们比较容易地记住名字,如www.baidu.com. 它们允许服务器改变IP地址,但是还用同样的名字. 作为一个例子,让我们看一下查询    www.baidu.com  首先,您的程序会和操作系统配置文件指定的本地名称服务器通信.这个服务器是一个递归的名称服务器,它收到请求并以适当的方式传递下去,它会为您完成大量工作. 递归服务器做的第一件事情是询问.co

第十七章 Python网络编程

Socket简介 在网络上的两个程序通过一个双向的通信连接实现数据的交换,这个链接的一端称为一个Socket(套接字),用于描述IP地址和端口. 建立网络通信连接至少要一对端口号(Socket),Socket本质是编程接口(API),对TCP/IP的封装,提供了网络通信能力. 每种服务都打开一个Socket,并绑定到端口上,不同的端口对应不同的服务,就像http对应80端口. Socket是面向C/S(客户端/服务器)模型设计,客户端在本地随机申请一个唯一的Socket号,服务器拥有公开的soc

python网络编程基础--socket的简介,以及使用socket来搭建一个简单的udp小程序

socket介绍: socket(简称套接字),是进程间通讯的一个工具,他能实现把数据从一方传输到另一方,完成不同电脑上进程之间的通讯,它好比数据的搬运工.socket应用:不夸张来说,只要跟网络相关的应用程序或者软件都使用到了socket, 比如:微信,qq等使用socket创建udp网络程序的流程:1,创建客户端套接字2,发送/接收数据3,关闭套接字使用程序展现流程 :(使用的 ide为pycharm):1,首先创建socket,在 Python 中 使用socket 模块的函数 socke

python网络编程基础

Socket(套接字)始于Unix,即人们所说的BSD Unix.socket家族有两种:基于文件系统的和基于网络的.第一种是基于文件系统的,地址家族表示为:AF_UNIX(或AF_LOCAL);第二种是网络Socket,是基于网络的,地址家族表示为AF_INET(AF_INET6表示ipv6).在Python 2.5 中加入了一种 Linux 套接字的支持:AF_NETLINK(无连接[见下])套接字家族让用户代码与内核代码之间的 IPC 可以使用标准 BSD 套接字接口.Python 只支持

python 网络编程第三版

为服务端增加多线程解决方案 1.服务端代码如下: ***这个版本并没有真正的起到多线程的作用,主要原因在于t.join():以后的版本会改进这个问题*** #!/usr/bin/python #!coding:utf-8 import os,sys,time from socket import * import threading def handleClient(conn): print '[info] handleClient is :{0}'.format(os.getpid()) wh