python多线程知识-实用实例

python多线程使用场景:IO操作,不适合CPU密集操作型任务
 
1、多个线程内存共享
2、线程同时修改同一份数据需要加锁,mutex互斥锁
3、递归锁:多把锁,锁中有锁
4、python多线程,同一时间只有颗CPU在执行。
 
启动线程:
 1 import threading
 2 def run(name)
 3     print("run thread....")
 4 
 5 #创建进程对象,target=方法名,args=(参数1,参数b,)
 6 t = threading.Thread(target=run,args=(n,))
 7 #设置守护线程
 8 t.setDaemon(True)
 9 #启动线程
10 t.start()
11 #等待线程结束
12 t.jion()

型号量使用(线程池)

 1 import threading
 2 import time
 3 
 4 def run(n):
 5     #加锁
 6     semaphore.acquire()
 7     print("Look:%s"%n)
 8     time.sleep(0.5)
 9     #释放锁
10     semaphore.release()
11 
12 if __name__ == "__main__":
13     #同时准许5个线程
14     semaphore = threading.BoundedSemaphore(5)
15     tlist = []
16     #设置多少个线程
17     for i in range(33):
18         t = threading.Thread(target=run,args=(i,))
19         t.start()
20         tlist.append(t)
21     for r in tlist:
22         r.jion()
原文地址:https://www.cnblogs.com/shangmo/p/9001946.html