1

with some help I could run a process in python, Now I wan't to share a value betwenn the two tasks. I can set the value inside the init, but I can't change it inside the run method.

And by the way: how to kill the process when the main process stops?

from multiprocessing import Process, Value

import serial
import time


class P(Process):
    def __init__(self, num):
        num.value = 15
        super(P, self).__init__()
    def run(self):
        while True:
            num.value = num.value + 1
            print("run simple process")
            time.sleep(0.5)

def main():
    while True:
        print("run main")
        print (num.value)
        time.sleep(2.5)


if __name__ == "__main__":
    num = Value('d', 0.0)
    p = P(num)
    p.start()
    #p.join()
    main()

1 Answer 1

2

In your simplified case you just passed num value upon initialization time.
To be able to access that value in other process's methods - set it as a state of the process:

class P(Process):
    def __init__(self, num):
        self.num = num
        self.num.value = 15
        super(P, self).__init__()

    def run(self):
        while True:
            self.num.value += 1
            print("run simple process")
            time.sleep(0.5)

For a more "serious" cases - consider using Managers and Synchronization primitives.

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

4 Comments

when I'm using p.terminate() in main() to stop the process I got error in the VSCode. It stops the process, but throws these errors. Is there a cleaner way to stop a process.
@bluelemonade, you wrote "these errors" but you did not even post the error text
ok, on the end I call print.terminate() to close a bunch of serial ports and stop the processes. but I get some errors. when I start the script again the ports are already open... def main(): global processList while True: print("main") time.sleep(1.0) for process in processList: print ("kill process") process.terminate() that's the error: exitcode = _main(fd) Traceback (most recent call last): File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 118, in _main
@bluelemonade, can you post the error text (not only the file path) ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.