进程引包multiprocessing,进程是资源最小单位,每个进程拥有自己的资源,不涉及资源互斥
线程引包threading,线程是是cpu调度的最小单位,可以访问共享资源,使用互斥锁对共享资源加锁
import threading import multiprocessing import time count = 0 mutex = threading.Lock() def test(): global count mutex.acquire() for i in range(100): count += 1 time.sleep(0.02) mutex.release() print(f"thread is {threading.current_thread()}count is {count}") def test1(): global count mutex.acquire() for i in range(100): count += 1 time.sleep(0.02) mutex.release() print(f"thread is {threading.current_thread()}count is {count}") if __name__ == '__main__': threading.Thread(target=test).start() threading.Thread(target=test1).start() # multiprocessing.Process(target=test).start() # multiprocessing.Process(target=test).start()加锁前:原因对count竞争性操作
thread is <Thread(Thread-1, started 5872)>count is 200
thread is <Thread(Thread-2, started 8124)>count is 200
加锁后输出:
thread is <_MainThread(MainThread, started 5960)>count is 100
thread is <_MainThread(MainThread, started 10076)>count is 100