线程
概念
线程时最小的执行单元,依赖于进程,是一个 CPU 执行时所需要的一串指令。
分类
主线程、子线程、守护线程
创建线程
方法一:将函数作为参数传入threading.Thread中
import threading,time#导入threading模块
def run(a):#以随意定义方法,不一定是run
time.sleep(2)
print('this is thread%d'%a)
thread_list=[]#定义空列表
for i in range(10):
t=threading.Thread(target=run, args=[i, ])#初始化线程
thread_list.append(t)#将初始化的线程添加到列表中
for item in thread_list:#批量开启线程
item.start()
结果:
2秒后出现以下
this is thread0
this is thread1
this is thread6
this is thread5
this is thread3
this is thread4
this is thread2
this is thread8
this is thread7
this is thread9
Process finished with exit code 0
方法二:定义一个类,继承threading.thread,重写run方法
import threading,time#导入threading模块
class mythread(threading.Thread):
def __init__(self,n):
super(mythread, self).__init__() # 重构run函数必须要写
self.n=n
def run(self):#这里只能是run方法,不要和上面搞混了,上面可以随意定义方法
time.sleep(2)
print('this is thread%d' % self.n)
if __name__=="__main__":
thread_list = [] # 定义空列表
for i in range(10):
t=mythread(i)
thread_list.append(t)
for item in thread_list: # 批量开启线程
item.start()
结果:
2s后出现以下
this is thread2
this is thread3
this is thread0
this is thread1
this is thread8
this is thread7
this is thread6
this is thread4
this is thread5
this is thread9
Process finished with exit code 0
join方法
使线程执行完才结束
守护线程
setDaemon(),主线程执行完就结束
线程锁
很多线程同时修改1个数据时,容易出错,此时给线程加一把锁,即该线程在执行某项操作时,别的线程不可执行,直至解锁后别的线程才能执行该项操作
import threading,time#导入threading模块
lock=threading.Lock()#定义一把线程锁
num=0
class mythread(threading.Thread):
def run(self):
lock.acquire()#锁上
global num
num=num+1
lock.release()#打开
list=[]
for i in range(100000):
t=mythread()
list.append(t)
for item in list:
item.start()
print(num)#打印结果
结果:
100000
Process finished with exit code 0
递归锁
threading.Lock()只能锁一层,不能锁上锁。threading.RLock()可以在锁内再锁。
还没有评论,来说两句吧
