通过类创建子线程&同步锁

时间:2022-05-09 19:19:06

一、通过类创建子线程

 import threading
class MyThread(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num = num
def run(self):
print('running on number %s' %self.num)
if __name__ == '__main__':
t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()

二、同步锁

import time
import threading
def cal():
global num
r.acquire() #上锁
temp = num
time.sleep(0.001)
num = temp-1
r.release() #开锁
1.被上锁的代码不执行完,GIL锁不释放,线程不切换
2.开锁后,多线程正常运行
 num = 100
thread_list = []
r = threading.Lock() #创建锁
for i in range(100):
t = threading.Thread(target=cal)
t.start()
thread_list.append(t) for t in thread_list: #等待所有子线程执行完毕
t.join() print(num)