In multi-process, each process opens up space, and the data is not shared. If you want to share its data in each process, you need to use the Manager
from multiprocessing import Process
from multiprocessing import Manager
from multiprocessing import Lock
def change_dic(dic,lock):
# lock.acquire() # 互斥锁上锁
dic["count"] -= 1
# print(dic)
# lock.release() # 互斥锁解锁
if __name__ == "__main__":
m = Manager()
dic = m.dict({
"count":100})
lock = Lock()
p_1 = []
for i in range(100):
# p = Process(target=change_dic,args=(dic,))
p = Process(target=change_dic,args=(dic,lock))
p.start()
p_1.append(p)
for p in p_1:
p.join()
print(dic)
Incidentally, here: data in multiple threads is shared (resource data in the same process is shared for multiple threads in the process), for example (a dictionary is used here for example, if the incoming variable cannot be Apply directly):
from threading import Thread
def task(dic):
dic["count"] -= 1
print(dic["count"])
if __name__ == "__main__":
dic = {
"count":50}
for i in range(50):
t = Thread(target=task,args=(dic,))
t.start()