笨方法学 python3进阶篇_Python学习进阶篇(三)

Socket

I/O多路复用

I/O多路复用指:通过一种机制,可以监视多个描述符,一旦某个描述符就绪(一般是读就绪或者写就绪),能够通知程序进行相应的读写操作。

Linux

Linux中的 select,poll,epoll 都是IO多路复用的机制。

select

select最早于1983年出现在4.2BSD中,它通过一个select()系统调用来监视多个文件描述符的数组,当select()返回后,该数组中就绪的文件描述符便会被内核修改标志位,使得进程可以获得这些文件描述符从而进行后续的读写操作。

select目前几乎在所有的平台上支持,其良好跨平台支持也是它的一个优点,事实上从现在看来,这也是它所剩不多的优点之一。

select的一个缺点在于单个进程能够监视的文件描述符的数量存在最大限制,在Linux上一般为1024,不过可以通过修改宏定义甚至重新编译内核的方式提升这一限制。

另外,select()所维护的存储大量文件描述符的数据结构,随着文件描述符数量的增大,其复制的开销也线性增长。同时,由于网络响应时间的延迟使得大量TCP连接处于非活跃状态,但调用select()会对所有socket进行一次线性扫描,所以这也浪费了一定的开销。

poll

poll在1986年诞生于System V Release 3,它和select在本质上没有多大差别,但是poll没有最大文件描述符数量的限制。

poll和select同样存在一个缺点就是,包含大量文件描述符的数组被整体复制于用户态和内核的地址空间之间,而不论这些文件描述符是否就绪,它的开销随着文件描述符数量的增加而线性增大。

另外,select()和poll()将就绪的文件描述符告诉进程后,如果进程没有对其进行IO操作,那么下次调用select()和poll()的时候将再次报告这些文件描述符,所以它们一般不会丢失就绪的消息,这种方式称为水平触发(Level Triggered)。

epoll

直到Linux2.6才出现了由内核直接支持的实现方法,那就是epoll,它几乎具备了之前所说的一切优点,被公认为Linux2.6下性能最好的多路I/O就绪通知方法。

epoll可以同时支持水平触发和边缘触发(Edge Triggered,只告诉进程哪些文件描述符刚刚变为就绪状态,它只说一遍,如果我们没有采取行动,那么它将不会再次告知,这种方式称为边缘触发),理论上边缘触发的性能要更高一些,但是代码实现相当复杂。

epoll同样只告知那些就绪的文件描述符,而且当我们调用epoll_wait()获得就绪文件描述符时,返回的不是实际的描述符,而是一个代表就绪描述符数量的值,你只需要去epoll指定的一个数组中依次取得相应数量的文件描述符即可,这里也使用了内存映射(mmap)技术,这样便彻底省掉了这些文件描述符在系统调用时复制的开销。

另一个本质的改进在于epoll采用基于事件的就绪通知方式。在select/poll中,进程只有在调用一定的方

Python

Python中有一个select模块,其中提供了:select、poll、epoll三个方法,分别调用系统的 select,poll,epoll 从而实现IO多路复用。

Windows Python:

提供: select

Mac Python:

提供: select

Linux Python:

提供: select、poll、epoll

注意:网络操作、文件操作、终端操作等均属于IO操作,对于windows只支持Socket操作,其他系统支持其他IO操作,但是无法检测 普通文件操作 自动上次读取是否已经变化。

select/epoll/poll区别:

select —— 对文件描述符的个数有限制,系统内部循环、遍历、读取

poll —— 内部循环操作

epoll——系统底层内部实现了事件异步回调的机制

对于select方法:

句柄列表11, 句柄列表22, 句柄列表33 = select.select(句柄序列1, 句柄序列2, 句柄序列3, 超时时间)

参数: 可接受四个参数(前三个必须)

返回值:三个列表

select方法用来监视文件句柄,如果句柄发生变化,则获取该句柄。

1、当 参数1 序列中的句柄发生可读时(accetp和read),则获取发生变化的句柄并添加到 返回值1 序列中

2、当 参数2 序列中含有句柄时,则将该序列中所有的句柄添加到 返回值2 序列中

3、当 参数3 序列中的句柄发生错误时,则将该发生错误的句柄添加到 返回值3 序列中

4、当 超时时间 未设置,则select会一直阻塞,直到监听的句柄发生变化

当 超时时间 = 1时,那么如果监听的句柄均无任何变化,则select会阻塞 1 秒,之后返回三个空列表,如果监听的句柄有变化,则直接执行。

此处的Socket服务端相比与原生的Socket,他支持当某一个请求不再发送数据时,服务器端不会等待而是可以去处理其他请求的数据。但是,如果每个请求的耗时比较长时,select版本的服务器端也无法完成同时操作。

利用select监听终端操作实例

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import select

import threading

import sys

while True:

readable, writeable, error = select.select([sys.stdin,],[],[],1)

if sys.stdin in readable:

print 'select get stdin',sys.stdin.readline()

利用select实现伪同时处理多个Socket客户端请求:服务端

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import socket

import select

sk1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sk1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

sk1.bind(('127.0.0.1',8002))

sk1.listen(5)

sk1.setblocking(0)

inputs = [sk1,]

while True:

readable_list, writeable_list, error_list = select.select(inputs, [], inputs, 1)

for r in readable_list:

# 当客户端第一次连接服务端时

if sk1 == r:

print 'accept'

request, address = r.accept()

request.setblocking(0)

inputs.append(request)

# 当客户端连接上服务器之后,再次发送数据时

else:

received = r.recv(1024)

# 当正常接收客户端发送的数据时

if received:

print 'received data:', received

# 当客户端关闭程序时

else:

inputs.remove(r)

sk1.close()

利用select实现伪同时处理多个Socket客户端请求:客户端

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import socket

ip_port = ('127.0.0.1',8002)

sk = socket.socket()

sk.connect(ip_port)

while True:

inp = raw_input('please input:')

sk.sendall(inp)

sk.close()

此处的Socket服务端相比与原生的Socket,他支持当某一个请求不再发送数据时,服务器端不会等待而是可以去处理其他请求的数据。但是,如果每个请求的耗时比较长时,select版本的服务器端也无法完成同时操作。

SocketServer模块

SocketServer内部使用 IO多路复用 以及 “多线程” 和 “多进程” ,从而实现并发处理多个客户端请求的Socket服务端。即:每个客户端请求连接到服务器时,Socket服务端都会在服务器是创建一个“线程”或者“进程” 专门负责处理当前客户端的所有请求。

ThreadingTCPServer

ThreadingTCPServer实现的Soket服务器内部会为每个client创建一个 “线程”,该线程用来和客户端进行交互。

1、ThreadingTCPServer基础

使用ThreadingTCPServer:

创建一个继承自 SocketServer.BaseRequestHandler 的类

类中必须定义一个名称为 handle 的方法

启动ThreadingTCPServer

SocketServer实现服务器

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import SocketServer

class MyServer(SocketServer.BaseRequestHandler):

def handle(self):

# print self.request, self.client_address, self.server

conn = self.request

conn.sendall('欢迎致电 10086,请输入1xxx,0转人工服务')

Flag = True

while Flag:

data = conn.recv(1024)

if data == 'exit':

Flag = False

elif data == '0':

conn.sendall('通过可能会被录音.balabala一大推')

else:

conn.sendall('请重新输入.')

if __name__ == '__main__':

server = SocketServer.ThreadingTCPServer(('127.0.0.1',8009),MyServer)

server.serve_forever()

客户端

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import socket

ip_port = ('127.0.0.1',8009)

sk = socket.socket()

sk.connect(ip_port)

sk.settimeout(5)

while True:

data = sk.recv(1024)

print 'receive:',data

inp = raw_input('please input:')

sk.sendall(inp)

if inp == 'exit':

break

sk.close()

2、ThreadingTCPServer源码剖析

ThreadingTCPServer的类图关系如下:

内部调用流程为:

启动服务端程序

执行 TCPServer.__init__ 方法,创建服务端Socket对象并绑定 IP 和 端口

执行 BaseServer.__init__ 方法,将自定义的继承自SocketServer.BaseRequestHandler 的类 MyRequestHandle赋值给 self.RequestHandlerClass

执行 BaseServer.server_forever 方法,While 循环一直监听是否有客户端请求到达 ...

当客户端连接到达服务器

执行 ThreadingMixIn.process_request 方法,创建一个 “线程” 用来处理请求

执行 ThreadingMixIn.process_request_thread 方法

执行 BaseServer.finish_request 方法,执行 self.RequestHandlerClass() 即:执行 自定义 MyRequestHandler 的构造方法(自动调用基类BaseRequestHandler的构造方法,在该构造方法中又会调用 MyRequestHandler的handle方法)

ThreadingTCPServer相关源码:

# BaseServer

class BaseServer:

"""Base class for server classes.

Methods for the caller:

- __init__(server_address, RequestHandlerClass)

- serve_forever(poll_interval=0.5)

- shutdown()

- handle_request() # if you do not use serve_forever()

- fileno() -> int # for select()

Methods that may be overridden:

- server_bind()

- server_activate()

- get_request() -> request, client_address

- handle_timeout()

- verify_request(request, client_address)

- server_close()

- process_request(request, client_address)

- shutdown_request(request)

- close_request(request)

- handle_error()

Methods for derived classes:

- finish_request(request, client_address)

Class variables that may be overridden by derived classes or

instances:

- timeout

- address_family

- socket_type

- allow_reuse_address

Instance variables:

- RequestHandlerClass

- socket

"""

timeout = None

def __init__(self, server_address, RequestHandlerClass):

"""Constructor. May be extended, do not override."""

self.server_address = server_address

self.RequestHandlerClass = RequestHandlerClass

self.__is_shut_down = threading.Event()

self.__shutdown_request = False

def server_activate(self):

"""Called by constructor to activate the server.

May be overridden.

"""

pass

def serve_forever(self, poll_interval=0.5):

"""Handle one request at a time until shutdown.

Polls for shutdown every poll_interval seconds. Ignores

self.timeout. If you need to do periodic tasks, do them in

another thread.

"""

self.__is_shut_down.clear()

try:

while not self.__shutdown_request:

# XXX: Consider using another file descriptor or

# connecting to the socket to wake this up instead of

# polling. Polling reduces our responsiveness to a

# shutdown request and wastes cpu at all other times.

r, w, e = _eintr_retry(select.select, [self], [], [],

poll_interval)

if self in r:

self._handle_request_noblock()

finally:

self.__shutdown_request = False

self.__is_shut_down.set()

def shutdown(self):

"""Stops the serve_forever loop.

Blocks until the loop has finished. This must be called while

serve_forever() is running in another thread, or it will

deadlock.

"""

self.__shutdown_request = True

self.__is_shut_down.wait()

# The distinction between handling, getting, processing and

# finishing a request is fairly arbitrary. Remember:

#

# - handle_request() is the top-level call. It calls

# select, get_request(), verify_request() and process_request()

# - get_request() is different for stream or datagram sockets

# - process_request() is the place that may fork a new process

# or create a new thread to finish the request

# - finish_request() instantiates the request handler class;

# this constructor will handle the request all by itself

def handle_request(self):

"""Handle one request, possibly blocking.

Respects self.timeout.

"""

# Support people who used socket.settimeout() to escape

# handle_request before self.timeout was available.

timeout = self.socket.gettimeout()

if timeout is None:

timeout = self.timeout

elif self.timeout is not None:

timeout = min(timeout, self.timeout)

fd_sets = _eintr_retry(select.select, [self], [], [], timeout)

if not fd_sets[0]:

self.handle_timeout()

return

self._handle_request_noblock()

def _handle_request_noblock(self):

"""Handle one request, without blocking.

I assume that select.select has returned that the socket is

readable before this function was called, so there should be

no risk of blocking in get_request().

"""

try:

request, client_address = self.get_request()

except socket.error:

return

if self.verify_request(request, client_address):

try:

self.process_request(request, client_address)

except:

self.handle_error(request, client_address)

self.shutdown_request(request)

def handle_timeout(self):

"""Called if no new request arrives within self.timeout.

Overridden by ForkingMixIn.

"""

pass

def verify_request(self, request, client_address):

"""Verify the request. May be overridden.

Return True if we should proceed with this request.

"""

return True

def process_request(self, request, client_address):

"""Call finish_request.

Overridden by ForkingMixIn and ThreadingMixIn.

"""

self.finish_request(request, client_address)

self.shutdown_request(request)

def server_close(self):

"""Called to clean-up the server.

May be overridden.

"""

pass

def finish_request(self, request, client_address):

"""Finish one request by instantiating RequestHandlerClass."""

self.RequestHandlerClass(request, client_address, self)

def shutdown_request(self, request):

"""Called to shutdown and close an individual request."""

self.close_request(request)

def close_request(self, request):

"""Called to clean up an individual request."""

pass

def handle_error(self, request, client_address):

"""Handle an error gracefully. May be overridden.

The default is to print a traceback and continue.

"""

print '-'*40

print 'Exception happened during processing of request from',

print client_address

import traceback

traceback.print_exc() # XXX But this goes to stderr!

print '-'*40

# TCPServer

class TCPServer(BaseServer):

"""Base class for various socket-based server classes.

Defaults to synchronous IP stream (i.e., TCP).

Methods for the caller:

- __init__(server_address, RequestHandlerClass, bind_and_activate=True)

- serve_forever(poll_interval=0.5)

- shutdown()

- handle_request() # if you don't use serve_forever()

- fileno() -> int # for select()

Methods that may be overridden:

- server_bind()

- server_activate()

- get_request() -> request, client_address

- handle_timeout()

- verify_request(request, client_address)

- process_request(request, client_address)

- shutdown_request(request)

- close_request(request)

- handle_error()

Methods for derived classes:

- finish_request(request, client_address)

Class variables that may be overridden by derived classes or

instances:

- timeout

- address_family

- socket_type

- request_queue_size (only for stream sockets)

- allow_reuse_address

Instance variables:

- server_address

- RequestHandlerClass

- socket

"""

address_family = socket.AF_INET

socket_type = socket.SOCK_STREAM

request_queue_size = 5

allow_reuse_address = False

def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):

"""Constructor. May be extended, do not override."""

BaseServer.__init__(self, server_address, RequestHandlerClass)

self.socket = socket.socket(self.address_family,

self.socket_type)

if bind_and_activate:

try:

self.server_bind()

self.server_activate()

except:

self.server_close()

raise

def server_bind(self):

"""Called by constructor to bind the socket.

May be overridden.

"""

if self.allow_reuse_address:

self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

self.socket.bind(self.server_address)

self.server_address = self.socket.getsockname()

def server_activate(self):

"""Called by constructor to activate the server.

May be overridden.

"""

self.socket.listen(self.request_queue_size)

def server_close(self):

"""Called to clean-up the server.

May be overridden.

"""

self.socket.close()

def fileno(self):

"""Return socket file number.

Interface required by select().

"""

return self.socket.fileno()

def get_request(self):

"""Get the request and client address from the socket.

May be overridden.

"""

return self.socket.accept()

def shutdown_request(self, request):

"""Called to shutdown and close an individual request."""

try:

#explicitly shutdown. socket.close() merely releases

#the socket and waits for GC to perform the actual close.

request.shutdown(socket.SHUT_WR)

except socket.error:

pass #some platforms may raise ENOTCONN here

self.close_request(request)

def close_request(self, request):

"""Called to clean up an individual request."""

request.close()

# ThreadingMixIn

class ThreadingMixIn:

"""Mix-in class to handle each request in a new thread."""

# Decides how threads will act upon termination of the

# main process

daemon_threads = False

def process_request_thread(self, request, client_address):

"""Same as in BaseServer but as a thread.

In addition, exception handling is done here.

"""

try:

self.finish_request(request, client_address)

self.shutdown_request(request)

except:

self.handle_error(request, client_address)

self.shutdown_request(request)

def process_request(self, request, client_address):

"""Start a new thread to process the request."""

t = threading.Thread(target = self.process_request_thread,

args = (request, client_address))

t.daemon = self.daemon_threads

t.start()

# ThreadingTCPServer

class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass

RequestHandler相关源码

class BaseRequestHandler:

"""Base class for request handler classes.

This class is instantiated for each request to be handled. The

constructor sets the instance variables request, client_address

and server, and then calls the handle() method. To implement a

specific service, all you need to do is to derive a class which

defines a handle() method.

The handle() method can find the request as self.request, the

client address as self.client_address, and the server (in case it

needs access to per-server information) as self.server. Since a

separate instance is created for each request, the handle() method

can define arbitrary other instance variariables.

"""

def __init__(self, request, client_address, server):

self.request = request

self.client_address = client_address

self.server = server

self.setup()

try:

self.handle()

finally:

self.finish()

def setup(self):

pass

def handle(self):

pass

def finish(self):

pass

实例:

# 服务端

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import SocketServer

class MyServer(SocketServer.BaseRequestHandler):

def handle(self):

# print self.request,self.client_address,self.server

conn = self.request

conn.sendall('欢迎致电 10086,请输入1xxx,0转人工服务.')

Flag = True

while Flag:

data = conn.recv(1024)

if data == 'exit':

Flag = False

elif data == '0':

conn.sendall('通过可能会被录音.balabala一大推')

else:

conn.sendall('请重新输入.')

if __name__ == '__main__':

server = SocketServer.ThreadingTCPServer(('127.0.0.1',8009),MyServer)

server.serve_forever()

# 客户端

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import socket

ip_port = ('127.0.0.1',8009)

sk = socket.socket()

sk.connect(ip_port)

sk.settimeout(5)

while True:

data = sk.recv(1024)

print 'receive:',data

inp = raw_input('please input:')

sk.sendall(inp)

if inp == 'exit':

break

sk.close()

源码精简:

import socket

import threading

import select

def process(request, client_address):

print request,client_address

conn = request

conn.sendall('欢迎致电 10086,请输入1xxx,0转人工服务.')

flag = True

while flag:

data = conn.recv(1024)

if data == 'exit':

flag = False

elif data == '0':

conn.sendall('通过可能会被录音.balabala一大推')

else:

conn.sendall('请重新输入.')

sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sk.bind(('127.0.0.1',8002))

sk.listen(5)

while True:

r, w, e = select.select([sk,],[],[],1)

print 'looping'

if sk in r:

print 'get request'

request, client_address = sk.accept()

t = threading.Thread(target=process, args=(request, client_address))

t.daemon = False

t.start()

sk.close()

如精简代码可以看出,SocketServer的ThreadingTCPServer之所以可以同时处理请求得益于 select 和 Threading 两个东西,其实本质上就是在服务器端为每一个客户端创建一个线程,当前线程用来处理对应客户端的请求,所以,可以支持同时n个客户端链接(长连接)。

ForkingTCPServer

ForkingTCPServer和ThreadingTCPServer的使用和执行流程基本一致,只不过在内部分别为请求者建立 “线程” 和 “进程”。

基本使用:

#服务端

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import SocketServer

class MyServer(SocketServer.BaseRequestHandler):

def handle(self):

# print self.request,self.client_address,self.server

conn = self.request

conn.sendall('欢迎致电 10086,请输入1xxx,0转人工服务.')

Flag = True

while Flag:

data = conn.recv(1024)

if data == 'exit':

Flag = False

elif data == '0':

conn.sendall('通过可能会被录音.balabala一大推')

else:

conn.sendall('请重新输入.')

if __name__ == '__main__':

server = SocketServer.ForkingTCPServer(('127.0.0.1',8009),MyServer)

server.serve_forever()

#客户端

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import socket

ip_port = ('127.0.0.1',8009)

sk = socket.socket()

sk.connect(ip_port)

sk.settimeout(5)

while True:

data = sk.recv(1024)

print 'receive:',data

inp = raw_input('please input:')

sk.sendall(inp)

if inp == 'exit':

break

sk.close()

以上ForkingTCPServer只是将 ThreadingTCPServer 实例中的代码:

server = SocketServer.ThreadingTCPServer(('127.0.0.1',8009),MyRequestHandler)

变更为:

server = SocketServer.ForkingTCPServer(('127.0.0.1',8009),MyRequestHandler)

SocketServer的ThreadingTCPServer之所以可以同时处理请求得益于 select 和 os.fork 两个东西,其实本质上就是在服务器端为每一个客户端创建一个进程,当前新创建的进程用来处理对应客户端的请求,所以,可以支持同时n个客户端链接(长连接)。

源码剖析参考 ThreadingTCPServer。

Twisted

Twisted是一个事件驱动的网络框架,其中包含了诸多功能,例如:网络协议、线程、数据库管理、网络操作、电子邮件等。

事件驱动

简而言之,事件驱动分为二个部分:第一,注册事件;第二,触发事件。

自定义事件驱动框架,命名为:“弑君者”:

#!/usr/bin/env python

# -*- coding:utf-8 -*-

# event_drive.py

event_list = []

def run():

for event in event_list:

obj = event()

obj.execute()

class BaseHandler(object):

"""

用户必须继承该类,从而规范所有类的方法(类似于接口的功能)

"""

def execute(self):

raise Exception('you must overwrite execute')

程序员使用“弑君者框架”:

!/usr/bin/env python

# -*- coding:utf-8 -*-

from source import event_drive

class MyHandler(event_drive.BaseHandler):

def execute(self):

print 'event-drive execute MyHandler'

event_drive.event_list.append(MyHandler)

event_drive.run()

如上述代码,事件驱动只不过是框架规定了执行顺序,程序员在使用框架时,可以向原执行顺序中注册“事件”,从而在框架执行时可以出发已注册的“事件”。

基于事件驱动Socket

#!/usr/bin/env python

# -*- coding:utf-8 -*-

from twisted.internet import protocol

from twisted.internet import reactor

class Echo(protocol.Protocol):

def dataReceived(self, data):

self.transport.write(data)

def main():

factory = protocol.ServerFactory()

factory.protocol = Echo

reactor.listenTCP(8000,factory)

reactor.run()

if __name__ == '__main__':

main()

程序执行流程:

运行服务端程序

创建Protocol的派生类Echo

创建ServerFactory对象,并将Echo类封装到其protocol字段中

执行reactor的 listenTCP 方法,内部使用 tcp.Port 创建socket server对象,并将该对象添加到了 reactor的set类型的字段 _read 中

执行reactor的 run 方法,内部执行 while 循环,并通过 select 来监视 _read 中文件描述符是否有变化,循环中...

客户端请求到达

执行reactor的 _doReadOrWrite 方法,其内部通过反射调用 tcp.Port 类的 doRead 方法,内部 accept 客户端连接并创建Server对象实例(用于封装客户端socket信息)和 创建 Echo 对象实例(用于处理请求) ,然后调用 Echo 对象实例的 makeConnection 方法,创建连接。

执行 tcp.Server 类的 doRead 方法,读取数据,

执行 tcp.Server 类的 _dataReceived 方法,如果读取数据内容为空(关闭链接),否则,出发 Echo 的 dataReceived 方法

执行 Echo 的 dataReceived 方法

从源码可以看出,上述实例本质上使用了事件驱动的方法 和 IO多路复用的机制来进行Socket的处理。

#异步IO操作

#!/usr/bin/env python

# -*- coding:utf-8 -*-

from twisted.internet import reactor, protocol

from twisted.web.client import getPage

from twisted.internet import reactor

import time

class Echo(protocol.Protocol):

def dataReceived(self, data):

deferred1 = getPage('http://cnblogs.com')

deferred1.addCallback(self.printContents)

deferred2 = getPage('http://baidu.com')

deferred2.addCallback(self.printContents)

for i in range(2):

time.sleep(1)

print 'execute ',i

def execute(self,data):

self.transport.write(data)

def printContents(self,content):

print len(content),content[0:100],time.time()

def main():

factory = protocol.ServerFactory()

factory.protocol = Echo

reactor.listenTCP(8000,factory)

reactor.run()

if __name__ == '__main__':

main()

更多请见:

https://twistedmatrix.com/trac

http://twistedmatrix.com/documents/current/api/

Python线程

Threading用于提供线程相关的操作,线程是应用程序中工作的最小单元。

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import threading

import time

def show(arg):

time.sleep(1)

print 'thread'+str(arg)

for i in range(10):

t = threading.Thread(target=show, args=(i,))

t.start()

print 'main thread stop'

上述代码创建了10个“前台”线程,然后控制器就交给了CPU,CPU根据指定算法进行调度,分片执行指令。

更多方法:

start 线程准备就绪,等待CPU调度

setName 为线程设置名称

getName 获取线程名称

setDaemon 设置为后台线程或前台线程(默认)

如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,均停止

如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止

join 逐个执行每个线程,执行完毕后继续往下执行,该方法使得多线程变得无意义

run 线程被cpu调度后执行Thread类对象的run方法

线程锁

由于线程之间是进行随机调度,并且每个线程可能只执行n条执行之后,CPU接着执行其他线程。所以,可能出现如下问题:

# 未使用锁

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import threading

import time

gl_num = 0

def show(arg):

global gl_num

time.sleep(1)

gl_num +=1

print gl_num

for i in range(10):

t = threading.Thread(target=show, args=(i,))

t.start()

print 'main thread stop'

#!/usr/bin/env python

#coding:utf-8

import threading

import time

gl_num = 0

lock = threading.RLock()

def Func():

lock.acquire()

global gl_num

gl_num +=1

time.sleep(1)

print gl_num

lock.release()

for i in range(10):

t = threading.Thread(target=Func)

t.start()

事件

python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法 set、wait、clear。

事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么event.wait 方法时便不再阻塞。

clear:将“Flag”设置为False

set:将“Flag”设置为True

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import threading

def do(event):

print 'start'

event.wait()

print 'execute'

event_obj = threading.Event()

for i in range(10):

t = threading.Thread(target=do, args=(event_obj,))

t.start()

Python进程

from multiprocessing import Process

import threading

import time

def foo(i):

print 'say hi',i

for i in range(10):

p = Process(target=foo,args=(i,))

p.start()

注意:由于进程之间的数据需要各自持有一份,所以创建进程需要的非常大的开销。

进程数据共享

进程各自持有一份数据,默认无法共享数据。

#!/usr/bin/env python

#coding:utf-8

from multiprocessing import Process

from multiprocessing import Manager

import time

li = []

def foo(i):

li.append(i)

print 'say hi',li

for i in range(10):

p = Process(target=foo,args=(i,))

p.start()

print 'ending',li

#方法一,Array

from multiprocessing import Process,Array

temp = Array('i', [11,22,33,44])

def Foo(i):

temp[i] = 100+i

for item in temp:

print i,'----->',item

for i in range(2):

p = Process(target=Foo,args=(i,))

p.start()

#方法二:manage.dict()共享数据

from multiprocessing import Process,Manager

manage = Manager()

dic = manage.dict()

def Foo(i):

dic[i] = 100+i

print dic.values()

for i in range(2):

p = Process(target=Foo,args=(i,))

p.start()

p.join()

# 类型对应表

'c': ctypes.c_char, 'u': ctypes.c_wchar,

'b': ctypes.c_byte, 'B': ctypes.c_ubyte,

'h': ctypes.c_short, 'H': ctypes.c_ushort,

'i': ctypes.c_int, 'I': ctypes.c_uint,

'l': ctypes.c_long, 'L': ctypes.c_ulong,

'f': ctypes.c_float, 'd': ctypes.c_double

当创建进程时(非使用时),共享数据会被拿到子进程中,当进程中执行完毕后,再赋值给原值。

# 进程锁实例

#!/usr/bin/env python

# -*- coding:utf-8 -*-

from multiprocessing import Process, Array, RLock

def Foo(lock,temp,i):

"""

将第0个数加100

"""

lock.acquire()

temp[0] = 100+i

for item in temp:

print i,'----->',item

lock.release()

lock = RLock()

temp = Array('i', [11, 22, 33, 44])

for i in range(20):

p = Process(target=Foo,args=(lock,temp,i,))

p.start()

进程池

进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。

进程池中有两个方法:

apply

apply_async

#!/usr/bin/env python

# -*- coding:utf-8 -*-

from multiprocessing import Process,Pool

import time

def Foo(i):

time.sleep(2)

return i+100

def Bar(arg):

print arg

pool = Pool(5)

#print pool.apply(Foo,(1,))

#print pool.apply_async(func =Foo, args=(1,)).get()

for i in range(10):

pool.apply_async(func=Foo, args=(i,),callback=Bar)

print 'end'

pool.close()

pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。

协程

线程和进程的操作是由程序触发系统接口,最后的执行者是系统;协程的操作则是程序员。

协程存在的意义:对于多线程应用,CPU通过切片的方式来切换线程间的执行,线程切换时需要耗时(保存状态,下次继续)。协程,则只使用一个线程,在一个线程中规定某个代码块执行顺序。

协程的适用场景:当程序中存在大量不需要CPU的操作时(IO),适用于协程;

greenlet

#!/usr/bin/env python

# -*- coding:utf-8 -*-

from greenlet import greenlet

def test1():

print 12

gr2.switch()

print 34

gr2.switch()

def test2():

print 56

gr1.switch()

print 78

gr1 = greenlet(test1)

gr2 = greenlet(test2)

gr1.switch()

gevent

import gevent

def foo():

print('Running in foo')

gevent.sleep(0)

print('Explicit context switch to foo again')

def bar():

print('Explicit context to bar')

gevent.sleep(0)

print('Implicit context switch back to bar')

gevent.joinall([

gevent.spawn(foo),

gevent.spawn(bar),

])

# 遇到IO操作自动切换:

from gevent import monkey; monkey.patch_all()

import gevent

import urllib2

def f(url):

print('GET: %s' % url)

resp = urllib2.urlopen(url)

data = resp.read()

print('%d bytes received from %s.' % (len(data), url))

gevent.joinall([

gevent.spawn(f, 'https://www.python.org/'),

gevent.spawn(f, 'https://www.yahoo.com/'),

gevent.spawn(f, 'https://github.com/'),

])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值