使用Process的Python中的简单多线程

时间:2015-10-20 22:55:58

标签: python multithreading

我有一个相当简单的程序,我在python中编写,由于某种原因不起作用。它将在'join'行上方输出print语句,但不会在其后输出任何内容,包括更改。为什么呢?

from multiprocessing import Process
import time

x = 0

def main():
    global x
    p = Process(target=change)
    p.start()
    print(x)
    p.join()
   # time.sleep(5)


def change():
    global x
    x = x +1
    print(x)


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

我猜这是你想要的:

from threading import Lock, Thread

x = 0
lock = Lock()

def main():
    global x
    print(x)
    p = Thread(target=change, args=(1,))
    p2 = Thread(target=change, args=(2,))
    p.start()
    p2.start()
    p.join()
    p2.join()


def change(number):
    global x
    with lock:
        x = x + 1
        print('{} - coming from process #{}'.format(x, number))

if __name__ == '__main__':
    main()

输出:

0
1 - coming from process #1
2 - coming from process #2

你会注意到它不会起作用:

from multiprocessing import Process
from threading import Lock

x = 0
lock = Lock()

def main():
    global x
    print(x)
    p = Process(target=change, args=(1,))
    p2 = Process(target=change, args=(2,))
    p.start()
    p2.start()
    p.join()
    p2.join()


def change(number):
    global x
    with lock:
        x = x + 1
        print('{} - coming from process #{}'.format(x, number))

if __name__ == '__main__':
    main()

输出:

0
1 - coming from process #1
1 - coming from process #2
那是因为Process就像你的前辈一样 - 她并不关心你,并且在她上次看到它时会保留100%的东西。所以它首先是0,它将复制0,永远不会再看x。与她喜欢分享的Thread不同。