0

I want to pass a state attribute (bool) to a second process. The main process initializes this process and passes the regarding attribute within the constructor. Depending on this attribute the second process should print different values. The class 'TestClass' is located in separated file.

This is the sub process in a second file (let‘s call it subprocess.py), which doesn‘t print my desired results.

from multiprocessing import Process, Value    
import time
# this class is executed in a second process and reacts to changes in
# in the main process
class TestClass(Process):
    def __init__(self, value):
        Process.__init__(self)
        self.__current_state = value

    def run(self):
        while True:
            if bool(self.__current_state):
                print("Hello World")
            else:
                print("Not Hello World")
            time.sleep(0.5)

This is the main process, which is executed

import time 
from SubProcess import TestClass
# main procedur        
value_to_pass = Value('i', False).value    

test_obj = TestClass(value_to_pass)
test_obj.start()

while True:
    if bool(value_to_pass):
        value_to_pass = Value('i', False).value
    else:
        value_to_pass = Value('i', True).value
    # wait some time
    time.sleep(0.4)

At the end I would like to have an alternating output of Not Hello World and Hello World, which would successfully indicate the passing of the state argument.

At the moment it just outputs the print depending on my initialization of value_to_pass. It obviously does never change its value.

Using global attributes doesn't fit my requirements, because it is a question of different files. Furthermore using object attributes just fits if I use threads. Later I will use a RaspberryPi. I will handle multiple sensors with it. Hence, I'm forced to use multiple processes.

Thank you!

max_ger
  • 9
  • 2
  • Possible duplicate of [Python creating a shared variable between threads](https://stackoverflow.com/questions/17774768/python-creating-a-shared-variable-between-threads) – Hemerson Tacon Dec 20 '18 at 13:50
  • Within threads it is working fine even with object attributes. Moreover the main process and the sub process living in different files. – max_ger Dec 20 '18 at 13:56
  • I suggest that you edit your post to split the code block according to your real scenario in which you use 2 files. Moreover it seems you'll need to use sockets. Take a look [here](https://stackoverflow.com/questions/6920858/interprocess-communication-in-python). In this other [link](https://docs.python.org/3/library/ipc.html) you have more options – Hemerson Tacon Dec 20 '18 at 14:11

0 Answers0