一、多进程_进程安全(加锁)
1、目的
锁是为了确保数据的一致性,避免读写时,其他数据同时读取,会造成数据错误
线程安全:多线程读写的时候会加锁
线程不安全:没加锁,写起来会乱
2、加锁
#encoding=utf-8 from multiprocessing import Process, Lock import time def l(num,lock): lock.acquire() # 获得锁 time.sleep(0.2) print("Hello Num: %s" % (num)) lock.release() # 释放锁 if __name__ == '__main__': lock = Lock() # 创建一个共享锁实例 for num in range(50): Process(target = l, args = (num,lock)).start()
3、没加锁
#encoding=utf-8 from multiprocessing import Process, Lock import time def l(num): #lock.acquire() # 获得锁 time.sleep(0.2) print("Hello Num: %s" % (num)) #lock.release() # 释放锁 if __name__ == '__main__': #lock = Lock() # 创建一个共享锁实例 for num in range(50): Process(target = l, args = (num,)).start()
4、加上N把锁
#encoding=utf-8 import multiprocessing import time def worker(s, i): s.acquire() print(multiprocessing.current_process().name + " acquire") time.sleep(i) print(multiprocessing.current_process().name + " release") s.release() if __name__ == "__main__": # 设置限制最多3个进程同时访问共享资源 s = multiprocessing.Semaphore(3) for i in range(5): p = multiprocessing.Process(target = worker, args = (s, i * 2)) p.start()