1

Please consider the following code:

from multiprocessing import Process
import time

myArray = []

def myThread():
    counter = 0
    global myArray
    while True:
        myArray.append(counter)
        time.sleep(1)

counterThread = Process(target=myThread,)
counterThread.start()

while True:
    if len(myArray) > 0:
        print "Success"
    else:
        print ":("
        print myArray   
    time.sleep(1)

I am unable to get my success message, and i'm not sure why, I keep receiving :( and my terminal printing an empty array. I thought making the array global would mean any changes made at myThread() level would be applied?

3
  • 2
    But you aren't using threads, you're using processes. You can't share data across processes like that. Commented Aug 28, 2016 at 19:31
  • Awesome, Thanks very much, I have just changed from Processes to threads and got it working. If you would submit this as an answer, I will gladly accept Commented Aug 28, 2016 at 19:33
  • And threads wouldn't give any speedup. In any case you should rather use Pool.map or similar... Commented Aug 28, 2016 at 19:38

1 Answer 1

2

You are creating an second process, which has no access to data of the main process. You can use threading.Thread(target=myThread,), but you has to synchronize the access threading.Lock(), if you are using more than one thread.

You should terminate your thread, when you are finished and wait for the thread with athread.join().

See: https://docs.python.org/2/library/threading.html

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.