线程/进程锁、池,进程的数据共享
一、线程的锁
线程与进程共有五种锁
首先说说为什么要加锁
1、LOCK与RLOCK锁
1 import threading 2 import time 3 4 lock=threading.Lock() 5 def func(args): 6 time.sleep(1) 7 lock.acquire() 8 print(args) 9 lock.release() 10 11 for i in range(5): 12 t=threading.Thread() 13 t.start() 14
LOCK 与RLOCK用法相似,RLOCK可以多成加锁,然后多层解锁
2、semaphore 一次放行N个
1 import threading 2 import time 3 4 lock=threading.BoundedSemaphore(3) #设置一次放行三个进程 5 def func(args): 6 lock.acquire() 7 time.sleep(1) 8 print(args) 9 lock.release() 10 11 for i in range(9): 12 t=threading.Thread(target=func,args=(i,)) 13 t.start()
3、Condition 的两种方式
1 import threading 2 import time 3 4 lock=threading.Condition() 5 def func(args): 6 time.sleep(1) 7 lock.acquire() 8 lock.wait() 9 print(args) 10 lock.release() 11 12 for i in range(5): 13 t=threading.Thread(target=func,args=(i,)) 14 t.start() 15 16 while True: 17 inp = int(input("请输入任意数字")) 18 lock.acquire() 19 lock.notify(inp) 20 lock.release()
方式二、
1 import threading 2 import time 3 4 lock=threading.Condition() 5 def task(): 6 input(">>>>") 7 return True 8 9 def func(args): 10 time.sleep(1) 11 lock.acquire() 12 lock.wait_for(task) 13 print(args) 14 lock.release() 15 16 for i in range(5): 17 t=threading.Thread(target=func,args=(i,)) 18 t.start()
4、Event锁 一次放行所有线程
1 import threading 2 import time 3 lock=threading.Event() 4 def func(args): 5 time.sleep(1) 6 lock.wait() 7 print(args) 8 9 for i in range(5): 10 t=threading.Thread(target=func,args=(i,)) 11 t.start() 12 13 input("<<<<") 14 lock.set()
5、threading.local()原理
为每一个线程创建一个属于自己的内存来存放数据
1 import threading 2 import time 3 v=threading.local() 4 5 def func(args): 6 v.phone=args #存放数据 7 time.sleep(1) 8 print(v.phone,args) 9 10 for i in range(5): 11 t=threading.Thread(target=func,args=(i,)) 12 t.start()
6、线程池 设置每次可从线程池中调用的线程数
1 from concurrent.futures import ThreadPoolExecutor 2 import threading 3 import time 4 pool=ThreadPoolExecutor(2) # 线程池线程的可调用数 5 def func(args): 6 time.sleep(1) 7 print(args) 8 9 for i in range(5): 10 pool.submit(func,i)