What i want to do is check the Value "checker" periodically, but dont get the same value like def scraper, even i using global. i need this to make a contingency and if checker dont match the code restar the process.
from logging import WARN
from multiprocessing import Process
import time
import multiprocessing
checker = 0
def warn():
#DO STUFF
def changing():
global checker
while True:
#STUFFS
time.sleep(1)
checker += 1
print('Value:', checker)
def proc_start():
p_to_start = Process(target=changing)
p_to_start.start()
return p_to_start
def proc_stop(p_to_stop):
p_to_stop.terminate()
if __name__ == '__main__':
p = proc_start()
while True:
time.sleep(20)
if checker > 10:
checker = 0
else:
warn()
print('-----------------------RESTARTING-----------------------------------')
proc_stop(p)
p = proc_start()
>Solution :
The problem is that your sub-process and your main process see different versions of variable checker
each existing in its own address space unique to the process that is running.
To get this to work checker
needs to be created as in shared memory. In the code below a multiprocessing.Value
instance is created with a lock under which modifications to the common checker
value will be made so that each process sees consistent values. I also recommend that you familiarize yourself with the PEP8 Style Guide for Python. You will not want to go through life using a single space for indenting new blocks of code.
from logging import WARN
from multiprocessing import Process
import time
import multiprocessing
def warn():
#DO STUFF
...
def changing(checker):
while True:
#STUFFS
time.sleep(1)
with checker.get_lock():
checker.value += 1
print('Value:', checker.value)
def proc_start(checker):
p_to_start = Process(target=changing, args=(checker,))
p_to_start.start()
return p_to_start
def proc_stop(p_to_stop):
p_to_stop.terminate()
if __name__ == '__main__':
# Create shared unsigned long:
checker = multiprocessing.Value('L', 0, lock=True)
p = proc_start(checker)
while True:
time.sleep(20)
with checker.get_lock():
if checker.value > 10:
checker.value = 0
else:
warn()
print('-----------------------RESTARTING-----------------------------------')
proc_stop(p)
# Should checker be reset back to 0?
#checker.value = 0
p = proc_start(checker)
Prints:
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
Value: 6
Value: 7
Value: 8
Value: 9
Value: 10
Value: 11
Value: 12
Value: 13
Value: 14
Value: 15
Value: 16
Value: 17
Value: 18
Value: 19
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
Value: 6
Value: 7
Value: 8
Value: 9
etc.