multiprocessing、threading。 线程进程模块

模块 multiprocessing

Queue() 队列 创建a=queue() a.put() a.get()
Process() 进程 p=process(target=fun,args=[val,]) p.start() p.join() 创建方式2,创建类继承
Lock() 锁 lock=lock() lock.acquire() lock.release()
with lock:pass;

Semaphore() 信号量 Semaphore=lock() Semaphore.acquire() Semaphore.release()
JoinableQueue 管道(需要自己加锁)少用,left,right=Pipe() left.put() right.get()

Pool 进程池
p=Pool(5) #创建5个进程池
p.apply_async(func=get_url,args=[url,],callback=call) #为进程池添加任务,call是回调函数,回调参数是fun的return值
p.get()需要等进程完成,返回任务执行之后的值
p.close() # 不能再提交新的任务
p.join() # 等待池中的任务都执行完
p.map(func=wahaha,iterable=range(5)) # iterable接收一个可迭代对象

threading模块

Thread 线程 t=Thread(target=sayhi,args=('egon',)) t.start() 创建方式2,创建类继承

join , t.join() 等待
sAlive(): 返回线程是否活动的。
getName(): 返回线程名。
setName(): 设置线程名。
t.setDaemon(True)守护线程

threading模块提供的一些方法:
# threading.currentThread(): 返回当前的线程变量。
# threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
# threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

猜你喜欢

转载自www.cnblogs.com/python-by-xiaoma/p/10298549.html