search

Home  >  Q&A  >  body text

python3.x - python多线程如何修改数据?

代码比较简单

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]

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

迷茫迷茫2778 days ago563

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-04-18 10:22:02

    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

    reply
    0
  • Cancelreply