线程
一.线程与进程的区别
线程是一串指令集
进程是指令集的集合,即是多个线程组成的
二.全局锁
Python不能利用多核,到达并行。但当线程之间是io密集型可以通过切换到达效果。
三.实例一(以类方法写)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import threading 2 import time 3 class mythread(threading.Thread): 4 def __init__(self,name): 5 threading.Thread__init__(self) 6 self.name=name 7 def run(self)://重载父类的方法 8 print('%s is runing'%self.name) 9 time.sleep(1) 10 print('ending ') 11 T1=mythred('alex') 12 T2=mythread('bob') 13 T1.start() 14 T2.start() 15
五.实例三
1 import threading,time 2 3 4 num=100 5 lock=threading.Lock() 6 def reduce(): 7 global num
lock.acquire() 8 Temp=num 9 time.sleep(1) 10 num=Temp-1
lock.release()
for i in rang(100):
T= threading.THread(target=reduce)
T.start()
四.实例二
import threading import time def music(name): print('begin listening %s at %s'%(name,ctime())) sleep(2) print('end at %s'%ctime()) def move(name): print('begin watching %s at %s'%(name,ctime())) sleep(5) print('end at %s'%ctime()) Threads[] T1 = threading.thread(target=music,args=('七里香',)) Threads.append(T1) T2 = threading.thread(target=move,args=('阿甘正传',)) Threads.append(T2) //T2.setDaemon(True) 将T2设置为主线程的守护线程,即不用等待T2线程 for t in Threads: t.start //启动线程 t.join() print('main threading')