-1

So, i have example of code with two class functions with two infinite loops:

class Bot:
    def __init__(self):
        self.rocket = 0

    def func1(self):
        while True:
            self.rocket += 1

    def func2(self):
        while True:
            print(self.rocket)

I want them func1 and func2 to work at the same time. This is just an example, i dont need solution like:

class Bot:
    def __init__(self):
        self.rocket = 0

    def func1(self):
        while True:
            self.rocket += 1
            print(self.rocket)

Because i want a method how to run two functions with infinite loops in class ;) Thanks!I tried this, but causes errors:

from multiprocessing import Process

class Bot:
    def __init__(self):
        self.rocket = 0

    def func1(self):
        while True:
            self.rocket += 1

    def func2(self):
        while True:
            print(self.rocket)

    if __name__ == '__main__':
        p1 = Process(target=func1)
        p2 = Process(target=func2)
        p1.start()
        p2.start()
R Artur
  • 21
  • 3

1 Answers1

0
  1. You need a Bot instance to call func1 and func2 on
  2. Use threading.Thread and not multiprocessing.Process, to get details read What are the differences between the threading and multiprocessing modules? , the point to get for here is

    Threads share data by default; processes do not.

Using Process you'll see only 0 printing, the func1 process will has its own data and update rocket for him only and func2 Process won't be able to acess it, using Thread they will share the data

if __name__ == '__main__':
    from threading import Thread

    b = Bot()
    p1 = Thread(target=b.func1)
    p2 = Thread(target=b.func2)
    p1.start()
    p2.start()
azro
  • 53,056
  • 7
  • 34
  • 70