数据共享, 开销小, 速度快
from threading import Thread x = 3 def task(): global x x = 100 if __name__ == \'__main__\': t1 = Thread(target=task) t1.start() t1.join() print(f"===主线程{x}") """ ===主线程100 """ 线程的其他方法 from threading import Thread, current_thread, enumerate, activeCount import os import time x = 3 def task(): time.sleep(1) print(666) if __name__ == \'__main__\': t1 = Thread(target=task) t2 = Thread(target=task) t1.start() t2.start() print(t1.isAlive()) # 判断子线程是否存活 print(t1.getName()) # 获取子线程名字 t1.setName("子进程-1") # 修改子线程名字 print(t1.name) # 获取子线程的名字 *** print(current_thread()) # 获取当前线程的内容 print(enumerate()) # 获取当前进程下的所有线程,以列表形式展示 print(activeCount()) # 获取当前进程下的所有存活线程的数量 print(os.getpid()) """ True Thread-1 子进程-1 <_MainThread(MainThread, started 60668)> [<_MainThread(MainThread, started 60668)>, <Thread(子进程-1, started 55172)>, <Thread(Thread-2, started 62068)>] 3 61048 666 666 """ join 与 守护线程守护线程, 等待非守护子线程以及主线程结束之后, 结束
from threading import Thread import time def say_hi(name): print("你滚") time.sleep(2) print(f"{name} say hello") if __name__ == \'__main__\': t = Thread(target=say_hi, args=("egon",)) # t.setDaemon(True) # 必须在t.start()前设置, 两种方法都可以 t.daemon = True t.start() print("主线程") # 注意 线程的开启速度比进程要快的多 """ 你滚 主线程 """ from threading import Thread import time def foo(): print(123) time.sleep(1) print("end123") def bar(): print(456) time.sleep(3) print("end456") t1=Thread(target=foo) t2=Thread(target=bar) t1.daemon=True t1.start() t2.start() print("main-------") """ 123 456 main------- end123 end456 """ 互斥锁 from threading import Thread import time import random x = 100 def task(): global x temp = x time.sleep(random.randint(1, 3)) temp = temp - 1 x = temp if __name__ == \'__main__\': l1 = [] for i in range(100): t = Thread(target=task) l1.append(t) t.start() for i in l1: i.join() print(f\'主线程{x}\') """ 主线程99 """ # 多个任务共抢一个数据, 为了保证数据的安全性, 要让其串行 from threading import Thread from threading import Lock import time x = 100 def task(lock): lock.acquire() global x temp = x temp = temp - 1 x = temp lock.release() if __name__ == \'__main__\': mutex = Lock() l1 = [] for i in range(100): t = Thread(target=task,args=(mutex,)) l1.append(t) t.start() time.sleep(3) print(f\'主线程{x}\') """ 主线程0 """