源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

python线程、进程和协程详解

  • 时间:2020-01-11 17:59 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:python线程、进程和协程详解
[b]引言 [/b] 解释器环境:python3.5.1 我们都知道python网络编程的两大必学模块socket和socketserver,其中的socketserver是一个支持IO多路复用和多线程、多进程的模块。一般我们在socketserver服务端代码中都会写这么一句:
server = socketserver.ThreadingTCPServer(settings.IP_PORT, MyServer)
[code]ThreadingTCPServer[/code]这个类是一个支持多线程和TCP协议的socketserver,它的继承关系是这样的: class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass 右边的TCPServer实际上是它主要的功能父类,而左边的ThreadingMixIn则是实现了多线程的类,它自己本身则没有任何代码。 MixIn在python的类命名中,很常见,一般被称为“混入”,戏称“乱入”,通常为了某种重要功能被子类继承。
class ThreadingMixIn:
  
 daemon_threads = False
 
 def process_request_thread(self, request, client_address):  
  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):
   
  t = threading.Thread(target = self.process_request_thread,
        args = (request, client_address))
  t.daemon = self.daemon_threads
  t.start()
在ThreadingMixIn类中,其实就定义了一个属性,两个方法。在process_request方法中实际调用的正是python内置的多线程模块threading。这个模块是python中所有多线程的基础,socketserver本质上也是利用了这个模块。 [b]一、线程[/b]
[url=http://jeffknupp.com/blog/2012/03/31/pythons-hardest-problem/]Python's Hardest Problem[/url] 译文:[url=http://www.oschina.net/translate/pythons-hardest-problem]Python 最难的问题[/url] 1.4 定时器(Timer) 定时器,指定n秒后执行某操作。很简单但很使用的东西。
from threading import Timer
def hello():
 print("hello, world")
t = Timer(1, hello) # 表示1秒后执行hello函数
t.start() 
1.5 队列 通常而言,队列是一种先进先出的数据结构,与之对应的是堆栈这种后进先出的结构。但是在python中,它内置了一个queue模块,它不但提供普通的队列,还提供一些特殊的队列。具体如下: [list=1] [*]queue.Queue :先进先出队列[/*] [*]queue.LifoQueue :后进先出队列[/*] [*]queue.PriorityQueue :优先级队列[/*] [*]queue.deque :双向队列 [/*] [/list] 1.5.1 Queue:先进先出队列 这是最常用也是最普遍的队列,先看一个例子。
import queue
q = queue.Queue(5)
q.put(11)
q.put(22)
q.put(33)

print(q.get())
print(q.get())
print(q.get())

Queue类的参数和方法: maxsize 队列的最大元素个数,也就是queue.Queue(5)中的5。当队列内的元素达到这个值时,后来的元素默认会阻塞,等待队列腾出位置。
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
[code]qsize() [/code]获取当前队列中元素的个数,也就是队列的大小 [code]empty() [/code]判断当前队列是否为空,返回True或者False [code]full() [/code]判断当前队列是否已满,返回True或者False put(self, block=True, timeout=None) 往队列里放一个元素,默认是阻塞和无时间限制的。如果,block设置为False,则不阻塞,这时,如果队列是满的,放不进去,就会弹出异常。如果timeout设置为n秒,则会等待这个秒数后才put,如果put不进去则弹出异常。 get(self, block=True, timeout=None) 从队列里获取一个元素。参数和put是一样的意思。 [code]join() [/code]阻塞进程,直到所有任务完成,需要配合另一个方法task_done。
def join(self):
 with self.all_tasks_done:
  while self.unfinished_tasks:
   self.all_tasks_done.wait()
[code]task_done()[/code] 表示某个任务完成。每一条get语句后需要一条task_done。
import queue
q = queue.Queue(5)
q.put(11)
q.put(22)
print(q.get())
q.task_done()
print(q.get())
q.task_done()
q.join()
1.5.2 LifoQueue:后进先出队列 类似于“堆栈”,后进先出。也较常用。
import queue
q = queue.LifoQueue()
q.put(123)
q.put(456)
print(q.get())
上述代码运行结果是:456 1.5.3 PriorityQueue:优先级队列 带有权重的队列,每个元素都是一个元组,前面的数字表示它的优先级,数字越小优先级越高,同样的优先级先进先出
q = queue.PriorityQueue()
q.put((1,"alex1"))
q.put((1,"alex2"))
q.put((1,"alex3"))
q.put((3,"alex3"))
print(q.get())
1.5.4 deque:双向队列 Queue和LifoQueue的“综合体”,双向进出。方法较多,使用复杂,慎用!
q = queue.deque()
q.append(123)
q.append(333)
q.appendleft(456)
q.pop()
q.popleft()
1.6 生产者消费者模型 利用多线程和队列可以搭建一个生产者消费者模型,用于处理大并发的服务。 在并发编程中使用生产者和消费者模式能够解决绝大多数并发问题。该模式通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据的速度。 为什么要使用生产者和消费者模式 在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程。在多线程开发当中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者处理完,才能继续生产数据。同样的道理,如果消费者的处理能力大于生产者,那么消费者就必须等待生产者。为了解决这个问题于是引入了生产者和消费者模式。 什么是生产者消费者模式 生产者消费者模式是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里取,阻塞队列就相当于一个缓冲区,平衡了生产者和消费者的处理能力。 这个阻塞队列就是用来给生产者和消费者解耦的。纵观大多数设计模式,都会找一个第三者出来进行解耦,如工厂模式的第三者是工厂类,模板模式的第三者是模板类。在学习一些设计模式的过程中,如果先找到这个模式的第三者,能帮助我们快速熟悉一个设计模式。 以上摘自方腾飞的《聊聊并发——生产者消费者模式》 下面是一个简单的厨师做包子,顾客吃包子的例子。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Liu Jiang
import time
import queue
import threading

q = queue.Queue(10)
def productor(i):
 while True:
  q.put("厨师 %s 做的包子!"%i)
  time.sleep(2)

def consumer(k):
 while True:
  print("顾客 %s 吃了一个 %s"%(k,q.get()))
  time.sleep(1)

for i in range(3):
 t = threading.Thread(target=productor,args=(i,))
 t.start()

for k in range(10):
 v = threading.Thread(target=consumer,args=(k,))
 v.start()

1.7 线程池 在使用多线程处理任务时也不是线程越多越好,由于在切换线程的时候,需要切换上下文环境,依然会造成cpu的大量开销。为解决这个问题,线程池的概念被提出来了。预先创建好一个较为优化的数量的线程,让过来的任务立刻能够使用,就形成了线程池。在python中,没有内置的较好的线程池模块,需要自己实现或使用第三方模块。下面是一个简单的线程池:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Liu Jiang

import queue
import time
import threading

class MyThreadPool:
 def __init__(self, maxsize=5):
  self.maxsize = maxsize
  self._q = queue.Queue(maxsize)
  for i in range(maxsize):
   self._q.put(threading.Thread)
   
 def get_thread(self):
  return self._q.get()
  
 def add_thread(self):
  self._q.put(threading.Thread)

def task(i, pool):
 print(i)
 time.sleep(1)
 pool.add_thread()

pool = MyThreadPool(5)
for i in range(100):
 t = pool.get_thread()
 obj = t(target=task, args=(i,pool))
 obj.start()

上面的例子是把线程类当做元素添加到队列内。实现方法比较糙,每个线程使用后就被抛弃,一开始就将线程开到满,因此性能较差。下面是一个相对好一点的例子:
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import queue
import threading
import contextlib
import time

StopEvent = object() # 创建空对象

class ThreadPool(object):

 def __init__(self, max_num, max_task_num = None):
  if max_task_num:
   self.q = queue.Queue(max_task_num)
  else:
   self.q = queue.Queue()
  self.max_num = max_num
  self.cancel = False
  self.terminal = False
  self.generate_list = []
  self.free_list = []

 def run(self, func, args, callback=None):
  """
  线程池执行一个任务
  :param func: 任务函数
  :param args: 任务函数所需参数
  :param callback: 任务执行失败或成功后执行的回调函数,回调函数有两个参数1、任务函数执行状态;2、任务函数返回值(默认为None,即:不执行回调函数)
  :return: 如果线程池已经终止,则返回True否则None
  """
  if self.cancel:
   return
  if len(self.free_list) == 0 and len(self.generate_list) < self.max_num:
   self.generate_thread()
  w = (func, args, callback,)
  self.q.put(w)

 def generate_thread(self):
  """
  创建一个线程
  """
  t = threading.Thread(target=self.call)
  t.start()

 def call(self):
  """
  循环去获取任务函数并执行任务函数
  """
  current_thread = threading.currentThread
  self.generate_list.append(current_thread)

  event = self.q.get()
  while event != StopEvent:

   func, arguments, callback = event
   try:
    result = func(*arguments)
    success = True
   except Exception as e:
    success = False
    result = None

   if callback is not None:
    try:
     callback(success, result)
    except Exception as e:
     pass

   with self.worker_state(self.free_list, current_thread):
    if self.terminal:
     event = StopEvent
    else:
     event = self.q.get()
  else:

   self.generate_list.remove(current_thread)

 def close(self):
  """
  执行完所有的任务后,所有线程停止
  """
  self.cancel = True
  full_size = len(self.generate_list)
  while full_size:
   self.q.put(StopEvent)
   full_size -= 1

 def terminate(self):
  """
  无论是否还有任务,终止线程
  """
  self.terminal = True

  while self.generate_list:
   self.q.put(StopEvent)

  self.q.empty()

 @contextlib.contextmanager
 def worker_state(self, state_list, worker_thread):
  """
  用于记录线程中正在等待的线程数
  """
  state_list.append(worker_thread)
  try:
   yield
  finally:
   state_list.remove(worker_thread)

# How to use
pool = ThreadPool(5)

def callback(status, result):
 # status, execute action status
 # result, execute action return value
 pass

def action(i):
 print(i)

for i in range(30):
 ret = pool.run(action, (i,), callback)

time.sleep(5)
print(len(pool.generate_list), len(pool.free_list))
print(len(pool.generate_list), len(pool.free_list))
# pool.close()
# pool.terminate()

[b]二、进程[/b] 在python中multiprocess模块提供了Process类,实现进程相关的功能。但是,由于它是基于fork机制的,因此不被windows平台支持。想要在windows中运行,必须使用if __name__ == '__main__:的方式,显然这只能用于调试和学习,不能用于实际环境。 (PS:在这里我必须吐槽一下python的包、模块和类的组织结构。在multiprocess中你既可以import大写的Process,也可以import小写的process,这两者是完全不同的东西。这种情况在python中很多,新手容易傻傻分不清。) 下面是一个简单的多进程例子,你会发现Process的用法和Thread的用法几乎一模一样。
from multiprocessing import Process

def foo(i):
 print("This is Process ", i)

if __name__ == '__main__':
 for i in range(5):
  p = Process(target=foo, args=(i,))
  p.start()

2.1 进程的数据共享 每个进程都有自己独立的数据空间,不同进程之间通常是不能共享数据,创建一个进程需要非常大的开销。
from multiprocessing import Process
list_1 = []
def foo(i):
 list_1.append(i)
 print("This is Process ", i," and list_1 is ", list_1)

if __name__ == '__main__':
 for i in range(5):
  p = Process(target=foo, args=(i,))
  p.start()

 print("The end of list_1:", list_1)

运行上面的代码,你会发现列表list_1在各个进程中只有自己的数据,完全无法共享。想要进程之间进行资源共享可以使用[code]queues/Array/Manager[/code]这三个multiprocess模块提供的类。 2.1.1 使用Array共享数据
from multiprocessing import Process
from multiprocessing import Array

def Foo(i,temp):
 temp[0] += 100
 for item in temp:
  print(i,'----->',item)

if __name__ == '__main__':
 temp = Array('i', [11, 22, 33, 44])
 for i in range(2):
  p = Process(target=Foo, args=(i,temp))
  p.start()

对于Array数组类,括号内的“i”表示它内部的元素全部是int类型,而不是指字符i,列表内的元素可以预先指定,也可以指定列表长度。概括的来说就是Array类在实例化的时候就必须指定数组的数据类型和数组的大小,类似temp = Array('i', 5)。对于数据类型有下面的表格对应: '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 2.1.2 使用Manager共享数据
from multiprocessing import Process,Manager

def Foo(i,dic):
 dic[i] = 100+i
 print(dic.values())

if __name__ == '__main__':
 manage = Manager()
 dic = manage.dict()
 for i in range(10):
  p = Process(target=Foo, args=(i,dic))
  p.start()
  p.join()

Manager比Array要好用一点,因为它可以同时保存多种类型的数据格式。 2.1.3 使用queues的Queue类共享数据
import multiprocessing
from multiprocessing import Process
from multiprocessing import queues

def foo(i,arg):
 arg.put(i)
 print('The Process is ', i, "and the queue's size is ", arg.qsize())

if __name__ == "__main__":
 li = queues.Queue(20, ctx=multiprocessing)
 for i in range(10):
  p = Process(target=foo, args=(i,li,))
  p.start()

这里就有点类似上面的队列了。从运行结果里,你还能发现数据共享中存在的脏数据问题。另外,比较悲催的是multiprocessing里还有一个Queue,一样能实现这个功能。 2.2 进程锁 为了防止和多线程一样的出现数据抢夺和脏数据的问题,同样需要设置进程锁。与threading类似,在multiprocessing里也有同名的锁类RLock, Lock, Event, Condition, Semaphore,连用法都是一样样的!(这个我喜欢)
from multiprocessing import Process
from multiprocessing import queues
from multiprocessing import Array
from multiprocessing import RLock, Lock, Event, Condition, Semaphore
import multiprocessing
import time

def foo(i,lis,lc):
 lc.acquire()
 lis[0] = lis[0] - 1
 time.sleep(1)
 print('say hi',lis[0])
 lc.release()

if __name__ == "__main__":
 # li = []
 li = Array('i', 1)
 li[0] = 10
 lock = RLock()
 for i in range(10):
  p = Process(target=foo,args=(i,li,lock))
  p.start()

2.3 进程池 既然有线程池,那必然也有进程池。但是,python给我们内置了一个进程池,不需要像线程池那样需要自定义,你只需要简单的from multiprocessing import Pool。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from multiprocessing import Pool
import time

def f1(args):
 time.sleep(1)
 print(args)

if __name__ == '__main__':
 p = Pool(5)
 for i in range(30):
  p.apply_async(func=f1, args= (i,))
 p.close()   # 等子进程执行完毕后关闭线程池
 # time.sleep(2)
 # p.terminate()  # 立刻关闭线程池
 p.join()

进程池内部维护一个进程序列,当使用时,去进程池中获取一个进程,如果进程池序列中没有可供使用的进程,那么程序就会等待,直到进程池中有可用进程为止。 进程池中有以下几个主要方法: [list=1] [*]apply:从进程池里取一个进程并执行[/*] [*]apply_async:apply的异步版本[/*] [*]terminate:立刻关闭线程池[/*] [*]join:主进程等待所有子进程执行完毕,必须在close或terminate之后[/*] [*]close:等待所有进程结束后,才关闭线程池[/*] [/list] [b]三、协程[/b] 线程和进程的操作是由程序触发系统接口,最后的执行者是系统,它本质上是操作系统提供的功能。而协程的操作则是程序员指定的,在python中通过yield,人为的实现并发处理。 协程存在的意义:对于多线程应用,CPU通过切片的方式来切换线程间的执行,线程切换时需要耗时。协程,则只使用一个线程,分解一个线程成为多个“微线程”,在一个线程中规定某个代码块的执行顺序。 协程的适用场景:当程序中存在大量不需要CPU的操作时(IO)。 在不需要自己“造轮子”的年代,同样有第三方模块为我们提供了高效的协程,这里介绍一下greenlet和gevent。本质上,gevent是对greenlet的高级封装,因此一般用它就行,这是一个相当高效的模块。 在使用它们之前,需要先安装,可以通过源码,也可以通过pip。 3.1 greenlet
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()

实际上,greenlet就是通过switch方法在不同的任务之间进行切换。 3.2 gevent
from gevent import monkey; monkey.patch_all()
import gevent
import requests

def f(url):
 print('GET: %s' % url)
 resp = requests.get(url)
 data = resp.text
 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/'),
])

通过joinall将任务f和它的参数进行统一调度,实现单线程中的协程。代码封装层次很高,实际使用只需要了解它的几个主要方法即可。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部