线程:指代码的运行过程
进程:指的是一个资源空间 (包含线程)
(1) 同一进程下,所有线程共享该进程下的资源
(2) 创建线程要小于进程
开启线程的方式
方式1: from threading import Thread import time def task(): print('xx') time.sleep(1) print('zz') if __name__== '__main__': t = Thread(target=task,) t.start() print('主')
from threading import Thread import time class auth(Thread): def run(self): print('xx %s' %self.name) time.sleep(1) print('zz') if __name__== '__main__': t = auth() t.start() print('主...')
线程互斥锁
from threading import Thread,Lock import time mutex = Lock() n = 100 def task(): global n mutex.acquire() test = n time.sleep(0.1) n = test -1 mutex.release() if __name__=='__main__': t_i = [] for i in range(100): t = Thread(target=task,) t_i.append(t) t.start() # t.join() for t in t_i: t.join() print(n)