python3.x - python多线程如何修改数据?
迷茫
迷茫 2017-04-18 10:20:02
0
1
564

代码比较简单

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]

有高手指点一下要如何实现吗?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
刘奇

Sorry, you are using multiprocessingmulti-process instead of multi-thread. The variables in each process are independent,

You should use threading, this is multi-threading

If you insist on using multiprocessing,就必须用共享变量,你可以将list里的数据存入Queue中,
Queuepython, you must use shared variables. You can store the data in list into Queue,
Queue It is a shared queue in python, used for multi-process communication

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template