code
# 由并发变成了串行,牺牲了运行效率,但避免了竞争
import os import time import random from multiprocessing import Process,Lock def work(lock,n): lock.acquire() print(‘%s: %s is running‘ % (n, os.getpid())) time.sleep(random.random()) print(‘%s: %s is done‘ % (n, os.getpid())) lock.release() if __name__ == ‘__main__‘: lock=Lock() for i in range(3): p=Process(target=work,args=(lock,i)) p.start()
outputs
macname@MacdeMacBook-Pro py % python3 cccccc.py 0: 57255 is running 0: 57255 is done 1: 57256 is running 1: 57256 is done 2: 57257 is running 2: 57257 is done macname@MacdeMacBook-Pro py %