标签:
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根据指定算法进行调度,分片执行指令。
更多方法:
线程锁
由于线程之间是进行随机调度,并且每个线程可能只执行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()
event
python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法 set、wait、clear。
事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么event.wait 方法时便不再阻塞。
#!/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() event_obj.clear() inp = raw_input(‘input:‘) if inp == ‘true‘: event_obj.set()
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() 进程锁实例
进程池
进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。
进程池中有两个方法:
#!/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()
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/‘), ])
#!/usr/bin/env python # -*- coding:utf-8 -*- import Queue import threading class ThreadPool(object): def __init__(self, max_num=20): self.queue = Queue.Queue(max_num) for i in xrange(max_num): self.queue.put(threading.Thread) def get_thread(self): return self.queue.get() def add_thread(self): self.queue.put(threading.Thread) """ pool = ThreadPool(10) def func(arg, p): print arg import time time.sleep(2) p.add_thread() for i in xrange(30): thread = pool.get_thread() t = thread(target=func, args=(i, pool)) t.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): self.q = queue.Queue() self.max_num = max_num 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 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) status = True except Exception as e: status = False result = e if callback is not None: try: callback(status, result) except Exception as e: pass if self.terminal: # False event = StopEvent else: with self.worker_state(self.free_list,current_thread): event = self.q.get() else: self.generate_list.remove(current_thread) @contextlib.contextmanager def worker_state(self,x,v): x.append(v) try: yield finally: x.remove(v) def close(self): num = len(self.generate_list) while num: self.q.put(StopEvent) num -= 1 # 终止线程(清空队列) def terminate(self): self.terminal = True while self.generate_list: self.q.put(StopEvent) self.q.empty() import time def work(i): time.sleep(1) print(i) pool = ThreadPool(10) for item in range(50): pool.run(func=work, args=(item,)) # pool.terminate() #立即终止所有线程
from concurrent.futures import ThreadPoolExecutor import time def f1(a): time.sleep(2) print(a) return 1 pool=ThreadPoolExecutor(5) for i in range(30): a=pool.submit(f1,i) # x=a.result()#获取返回值,如果有,会阻塞
标签:
原文地址:http://www.cnblogs.com/wanghzh/p/5606033.html