The target argument of the mp.Process
initializer is a reference to a function that will be called within a new process. But you are calling ask
and add
and passing their return values, which are None
, as the target arguments. This is clearly a problem.
The other two problems you have are:
- You can only call the
input
function from the main process. Generally this also has to be done by the initial, main thread of the main process - unless you go to special trouble that should be avoided.
- Variable
num
being referenced by the child processes you are creating are not referencing the same num
instances. Each process has its own address space and either inherits a copy of num
(e.g. under Linux) or creates a new num
in its own address space (e.g. under Windows). For all processes to see the same instance of num
it must be located in shared memory.
Note that I have modified the code so that add
ultimately terminates and I have added calls to time.sleep
to "slow everything down" so that the child process does not terminate before you have a chance to input a number:
import multiprocessing as mp
import time
def add(num):
while num.value < 10:
num.value += 1
time.sleep(1)
if __name__ == "__main__":
# A shared memory integer value initialized to 0:
num = mp.Value('i', 0)
p = mp.Process(target=add, args=(num,))
p.start()
x = input("Input: ")
print(x)
print(num.value)
p.join()
If you were using multithreading instead, which is not appropriate if function add
is mostly CPU-bound like your original version without the calls to time.sleep
is, then everything would be running in the same address space of a single process and there would be no problem with using a variable num
that is not in shared memory:
import threading
import time
num = 0
def add():
global num
while num < 10:
num += 1
time.sleep(1)
if __name__ == "__main__":
t = threading.Thread(target=add)
t.start()
x = input("Input: ")
print(x)
print(num)
t.join()