0

I have a fairly simple program that I am writing in python that does not work for some reason. It will output the print statement above the 'join' line but not anything after it, including in change. Why?

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()
4
  • 1
    Those aren't threads, they are processes. Each process has its own separate memory, with its own private copy of x. Commented Oct 20, 2015 at 22:59
  • Shouldnt they share a global X? Either way, change does not run. Commented Oct 20, 2015 at 23:00
  • 2
    This prints just fine when i run your code. Commented Oct 20, 2015 at 23:03
  • 1
    @Reid: No, they don't share a global x. That's threads. Processes only share things which they are specifically asked to share. Commented Oct 20, 2015 at 23:04

1 Answer 1

1

Im guessing this is what you want:

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()

output:

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

this you will notice will not work:

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()

output:

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

thats because Process is like your exwife - she doesnt care about you, and will keep 100% of the stuff when she last saw it. So its 0 first, and it will copy 0 and will never look at x again. Unlike Thread she likes to share.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.