单线程
import time
def run():
print("hello world")
time.sleep(1)
if __name__ == "__main__":
for i in range(5):
run()
多线程
import threading
import time
def run():
print("hello world")
time.sleep(1)
if __name__ == "__main__":
for i in range(5):
t1=threading.Thread(target=run)
t1.start()
当调用start()时,才会真正创建线程,并且开始执行
共享全局变量
import threading
g_num = 0
def text(n):
global g_num
for x in range(n):
g_num += x
g_num -= X
print(g_num)
if __name__ == '__main__':
t1 = threading.Thread(target=text,args=(10,))
t2 = threading.Thread(target=text,args=(10,))
t1.start()
t2.start()
列表当作实参传递传递到线程里
from threading import Thread
def work1(nums):
nums.append(22)
print("---in work1---",nums)
def work2(nums):
print("---in work2---",nums)
g_nums = [11,22,33]
t1 = Thread(target=work1,args=(g_nums,))
t1.start()
t2 = Thread(target=work2,args=(g_nums,))
t2.start()
- 如果多个线程同对同一个全局变量操作,会出现资源竞争问题,从而数据会不正确。
- 最简单的办法就是引用互斥锁。
#创建锁
mutex = threading.Lock()
#锁定
mutex.acquire()
#释放
mutex.release()
- 如果这个锁之前是没有上锁的,那么acquire不会堵塞,如果在调用acquire对这个锁上锁之前它已经被其它线程上了锁,那么此时acquire会堵塞,直到这个锁被解锁为止。
使用互斥锁解决一百万次加减问题
import threading
g_num = 0
def text(n):
global g_num
for x in range(n):
'''
lock.acquire()
g_num += x
g_num -= x
lock.release()
'''
#使用with关键字可以方便的完成互斥锁的开启和关闭
with lock:
g_num += x
g_num -= x
print(g_num)
if __name__ == '__main__':
lock = threading.Lock()
t1 = threading.Thread(target=text,args=(1000000,))
t2 = threading.Thread(target=text,args=(1000000,))
t1.start()
t2.start()
线程间的通信
Queue原理,put()放入数据,get()取出数据
import threading
import time
from queue import Queue
def producer(queue):
for i in range(100):
print('{}存入了{}'.format(threading.current_thread().name, i))
queue.put(i)
time.sleep(0.1)
return
def consumer(queue):
for x in range(100):
value = queue.get()
print('{}取到了{}'.format(threading.current_thread().name, value))
time.sleep(0.1)
if not value:
return
if __name__ == '__main__':
queue = Queue()
t1 = threading.Thread(target=producer, args=(queue,))
t2 = threading.Thread(target=consumer, args=(queue,))
t3 = threading.Thread(target=consumer, args=(queue,))
t4 = threading.Thread(target=consumer, args=(queue,))
t6 = threading.Thread(target=consumer, args=(queue,))
t1.start()
t2.start()
t3.start()
t4.start()
t6.start()
进程
创建一个进程,执行两个死循环
from multiprocessing import Process
import time
def run_proc():
"""子进程要执行的代码"""
while True:
print("----2----")
time.sleep(1)
if __name__=='__main__':
p = Process(target=run_proc)
p.start()
while True:
print("----1----")
time.sleep(1)
- 创建子进程时,只需要传入一个执行函数和函数的参数,创建一个Process实例,用start()方法启动。
- while True 没有 while 1 效率高
方法说明
Process(target[,name[,args[,kwargs]]]) - target:如果传递了函数的引用,可以任务这个子进程就执行这里的代码
- args:给target指定的函数传递的参数,以元组的方式传递
- kwargs:给target指定的函数传递命名参数
- name:给进程设定一个名字,可以不设定
Process创建实例对象的常用方法: - start():启动子进程实例(创建子进程)
- is_alive():判断进程子进程是否还在活着
- join([timeout]):是否等待子进程执行结束,或等待多少秒
- terminate():不管任务是否完成,立即终止子进程
Process创建的实例对象的常用属性: - name:当前进程的别名,默认为Process-N,N为从1开始递增的整数
- pid:当前进程的pid(进程号)
示例
from multiprocessing import Process
import os
from time import sleep
def run_proc(name,age,**kwargs):
for i in range(10):
print('子进程运行中,name=%s,age=%s,pid=%d...'%(name,age,os.getpid())) #os.getpid()获得当前进程的id
print(kwargs)
sleep(0.2)
if __name__ == '__main__':
p = Process(target=run_proc,args=('text',18),kwargs={"m":20})
p.start()
sleep(1)
p.terminate()
p.join()
Pool
- 开启过多的进程并不能提高你的效率,反而会降低你的效率,假设有500个任务,同时开启500个进程,这500个进程除了不能一起执行之外(cpu没有那么多核),操作系统调度这500个进程,让他们平均在4个或8个cpu上执行,这会占用很大的空间。
如果要启动大量的子进程,可以用进程池的方式批量创建子进程:
def task(n):
print('{}----->start'.format(n))
time.sleep(1)
print('{}------>end'.format(n))
if __name__ == '__main__':
p = Pool(8) # 创建进程池,并指定线程池的个数,默认是CPU的核数
for i in range(1, 11):
# p.apply(task, args=(i,)) # 同步执行任务,一个一个的执行任务,没有并发效果
p.apply_async(task, args=(i,)) # 异步执行任务,可以达到并发效果
p.close()
p.join()
- join:如果主进程的任务在执行到某一个阶段时,需要等待子进程执行完毕后才能继续执行,就需要有一种机制能够让主进程检测子进程是否运行完毕,在子进程执行完毕后才继续执行,否则一直在原地阻塞,这就是join方法的作用
- 进程池获取任务·的执行结果:
def task(n):
print('{}----->start'.format(n))
time.sleep(1)
print('{}------>end'.format(n))
return n ** 2
if __name__ == '__main__':
p = Pool(4)
for i in range(1, 11):
res = p.apply_async(task, args=(i,)) # res 是任务的执行结果
print(res.get()) # 直接获取结果的弊端是,多任务又变成同步的了
p.close()
# p.join() 不需要再join了,因为 res.get()本身就是一个阻塞方法
- 异步获取线程的执行结果:
import time
from multiprocessing.pool import Pool
def task(n):
print('{}----->start'.format(n))
time.sleep(1)
print('{}------>end'.format(n))
return n ** 2
if __name__ == '__main__':
p = Pool(4)
res_list = []
for i in range(1, 11):
res = p.apply_async(task, args=(i,))
res_list.append(res) # 使用列表来保存进程执行结果
for re in res_list:
print(re.get())
p.close()
进程间不能共享全局变量
from multiprocessing import Process
import os
nums = [11, 22]
def work1():
"""子进程要执行的代码"""
print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))
for i in range(3):
nums.append(i)
print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))
def work2():
"""子进程要执行的代码"""
nums.pop()
print("in process2 pid=%d ,nums=%s" % (os.getpid(), nums))
if __name__ == '__main__':
p1 = Process(target=work1)
p1.start()
p1.join()
p2 = Process(target=work2)
p2.start()
print('in process0 pid={} ,nums={}'.format(os.getpid(),nums))
线程和进程
功能
- 进程,能够完成多任务,比如 在一台电脑上能够同时运行多个QQ。
- 线程,能够完成多任务,比如 一个QQ中的多个聊天窗口。
定义的不同 - 进程是系统进行资源分配和调度的一个独立单位。
- 线程是进程的一个实体,是CPU调度和分派的基本单位,他是比进程更小的能独立运行的基本单位,线程自己基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计数器,一组寄存器和栈),但是它可与同属一个进程的其他的线程共享进程所拥有的全部资源。
区别 - 一个程序至少有一个进程,一个进程至少有一个线程.
- 线程的划分尺度小于进程(资源比进程少),使得多线程程序的并发性高。
- 进程在执行过程中拥有独立的内存单元,而多个线程共享内存,从而极大地提高了程序的运行效率
- 线线程不能够独立执行,必须依存在进程中
- 可以将进程理解为工厂中的一条流水线,而其中的线程就是这个流水线上的工人
优缺点 - 线程和进程在使用上各有优缺点:线程执行开销小,但不利于资源的管理和保护;而进程正相反。
进程间通信-Queue
from multiprocessing import Queue
q = Queue(3) #初始化一个Queue对象,最多可接收三条put消息
q.put("news1")
q.put("news2")
print(q.full()) #False
q.put("news3")
print(q.full()) #True
#因为消息列队已满下面的try都会抛出异常,第一个try会等待2秒后再抛出异常,第二个try会立刻抛出异常
try:
q.put("news4",True,2)
except:
print("消息队列已满,现有的消息数量:%s"%q.qsize())
try:
q.put_nowait("news4")
except:
print("消息队列已满,现有消息数量:%s"%q.qsize())
#推荐的方式,先判断消息列队是否已满,再写入
if not q.full():
q.put_nowait("news4")
#读取消息时,先判断消息队列是否为空,再读取
if not q.empty():
for i in range(q.qsize()):
print(q.get_nowait())
说明
初始化Queue()对象时(例如:q=Queue()),若括号中没有指定最大可接收的消息数量,或数量为负值,那么就代表可接受的消息数量没有上限(直到内存的尽头);
-
Queue.qsize():返回当前队列包含的消息数量;
-
Queue.empty():如果队列为空,返回True,反之False ;
-
Queue.full():如果队列满了,返回True,反之False;
-
Queue.get([block[, timeout]]):获取队列中的一条消息,然后将其从列队中移除,block默认值为True;
- 如果block使用默认值,且没有设置timeout(单位秒),消息列队如果为空,此时程序将被阻塞(停在读取状态),直到从消息列队读到消息为止,如果设置了timeout,则会等待timeout秒,若还没读取到任何消息,则抛出"Queue.Empty"异常;
- 如果block值为False,消息列队如果为空,则会立刻抛出"Queue.Empty"异常;
-
Queue.get_nowait():相当Queue.get(False);
-
Queue.put(item,[block[, timeout]]):将item消息写入队列,block默认值为True;
- 如果block使用默认值,且没有设置timeout(单位秒),消息列队如果已经没有空间可写入,此时程序将被阻塞(停在写入状态),直到从消息列队腾出空间为止,如果设置了timeout,则会等待timeout秒,若还没空间,则抛出"Queue.Full"异常;
- 如果block值为False,消息列队如果没有空间可写入,则会立刻抛出"Queue.Full"异常;
-
Queue.put_nowait(item):相当Queue.put(item, False);
使用Queue实现进程共享
我们以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据:
from multiprocess import Peocess,Queue
import os,time,random
#写数据进程执行的代码
def write(q):
for value in ['A','B','C']:
print('put %s to queue...'%value)
q.put(value)
time.sleep(random.random())
#读取数据进程执行的代码:
def read(q):
while True:
if not q.empty(): #empty:空
value = q.get(True)
print('get %s from queue'%value)
time.sleep(random.random())
else:
break
if __name__ == '__main__':
#父进程创建Queue,并传递各个子进程:
q = Queue()
pw = Process(target=write,args=(q,))
pr = Process(target=read,args=(q,))
#启动子进程pw,写入
pw.start()
#等待pw结束
pw.join()
#启动子进程pr
pr.start()
pr.join()
print("所有数据都写入并且读完")
进程池
当需要创建的子进程不多时,可以直接用Process,当多时可以用Pool方法,如果已经达到指定的最大值,就会排队等,直到有进程结束才能进,看下面实例:
from multiprocess import Pool
import os,time,random
def worker(msg):
t_start = time.time()
print("%s开始执行,进程号时%d"%(msg,os.getpid())
#random.random()随机生成0~1之间的浮点数
time.sleep(random.random()*2)
t_stop = time.time()
print(msg,"执行完毕,耗时%0.2f"%(t_stop-t_start))
po = Pool(3) #定义一个进程池,最大进程数3
for i in range(0,10):
#Pool().apply_async(要调用的目标,传递给目标的参数元组,))
#每次循环将会用空闲出来的子进程去调用目标
po.apply_async(worker,(i,))
print("----start----")
po.close() # 关闭进程池,关闭后po不再接收新的请求
po.join() # 等待po中所有子进程执行完成,必须放在close语句之后
print("-----end-----")
multiprocessing.Pool常用函数解析:
- apply_async(func[, args[, kwds]]) :使用非阻塞方式调用func(并行执行,堵塞方式必须等待上一个进程退出才能执行下一个进程), args为传递给func的参数列表,kwds为传递给func的关键字参数列表;
- close():关闭Pool,使其不再接受新的任务;
- terminate():不管任务是否完成,立即终止;
- join():主进程阻塞,等待子进程的退出, 必须在close或terminate之后使用;
进程池中的Queue
如果要使用Pool创建进程,就需要使用multiprocess.Manager()中的Queue(),而不是multiprocess.Queue(),否则会得到一条如下的错误信息:
RuntimeError: Queue objects should only be shared between processes through inheritance.
演示进程池中的进程如何通信:
#修改import中的Queue为Manager
from multiprocess import Manager,Pool
import os,time,random
def reader(q):
print("reader启动(%s),父进程为(%s)"%(os.getpid(),os.getppid()))
for i in range(q.qsize()):
print("reader从Queue获取到消息:%s"%q.get(True))
def writer(q):
print("writer启动(%s),父进程为(%s)" % (os.getpid(), os.getppid()))
for i in "helloworld":
q.put(i)
if __name__ == "__main__":
print("(%s) start" % os.getpid())
q = Manager().Queue() # 使用Manager中的Queue
po = Pool()
po.apply_async(writer, (q,))
time.sleep(1) # 先让上面的任务向Queue存入数据,然后再让下面的任务开始从中取数据
po.apply_async(reader, (q,))
po.close()
po.join()
print("(%s) End" % os.getpid())
协程
协程,又称微线程,纤程。英文名Coroutine。
协程是python个中另外一种实现多任务的方式,只不过比线程更小占用更小执行单元(理解为需要的资源)。 为啥说它是一个执行单元,因为它自带CPU上下文。这样只要在合适的时机, 我们可以把一个协程切换到另一个协程。 只要这个过程中保存或恢复 CPU上下文那么程序还是可以运行的。
协程和线程的差异
在实现多任务时, 线程切换从系统层面远不止保存和恢复 CPU上下文这么简单。 操作系统为了程序运行的高效性每个线程都有自己缓存Cache等等数据,操作系统还会帮你做这些数据的恢复操作,所以线程的切换非常耗性能。但是协程的切换只是单纯的操作CPU的上下文,所以一秒钟切换个上百万次系统都抗的住。
yield
import time
def work1():
while True:
print("----work1---")
yield
time.sleep(0.5)
def work2():
while True:
print("----work2---")
yield
time.sleep(0.5)
def main():
w1 = work1()
w2 = work2()
while True:
next(w1)
next(w2)
if __name__ == "__main__":
main()
执行结果:
----work1---
----work2---
----work1---
----work2---
----work1---
----work2---
----work1---
----work2---
----work1---
----work2---
----work1---
----work2---
...省略...