代码比较简单
import multiprocessing
import time
list1 = [1,2,3]
def func(msg):
list1[0] = 99
return "done " + msg
if __name__ == "__main__":
pool = multiprocessing.Pool(processes=4)
for i in range(10):
msg = "hello %d" % (i)
pool.apply_async(func, (msg,))
pool.close()
pool.join()
print (list1)
因为真实的环境比较多,所以简化了代码,我大概的需求就是list1是一个比较多的数据列表,然后在多线程处理的时候,每次更新其中一项数据...
但是我运行以后,发现list1还是[1,2,3] , 我理想应该是[99,2,3]
有高手指点一下要如何实现吗?
Sorry, you are using
multiprocessing
multi-process instead of multi-thread. The variables in each process are independent,You should use
threading
, this is multi-threadingIf you insist on using
multiprocessing
,就必须用共享变量,你可以将list
里的数据存入Queue
中,Queue
是python
, you must use shared variables. You can store the data inlist
intoQueue
,Queue
It is a shared queue inpython
, used for multi-process communication