niketp
niketp

Reputation: 459

How to run a threading function within a class?

I am trying to run a simple threading function within my simple class.

I am trying to call the Thread function within a method of a class. This Thread function within this method points to another method within the class. The way I tested it out is through the python terminal. Here is my class in increment_thread.py:

from threading import Thread
import time

class Increment:
    def __init__(self):
        self.count = 0

    def add_one(self):
        while True:
            self.count = self.count + 1
            time.sleep(5)

    def start(self):
        background_thread = Thread(target=add_one)
        background_thread.start()
        print("Started counting up")
        return

    def get_count(self):
        return print(self.count)

In order to test this, I run python in my terminal, which prompt the python terminal.

Then, I run the following lines:

from increment_thread import Increment
inc = Increment()
inc.get_count() # Yields 0
inc.start()

I expect the thread to start and indicate "Started counting up", but instead I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "~/python-sandbox/increment_thread.py", line 14, in start
    background_thread = Thread(target=add_one)
NameError: name 'add_one' is not defined

Is what I am trying to do possible?

Upvotes: 0

Views: 930

Answers (2)

Tom Bailey
Tom Bailey

Reputation: 319

In the Thread constructor should it not be target=self.add_one rather than target=add_one

To pass parameters:

from threading import Thread
import time

class Increment:

    count = None

    def __init__(self):
        self.count = 0

    def add_one(self, start_at=0):
      self.count = start_at
      while True:    
        self.count = self.count + 1
        time.sleep(5)

    def start_inc(self, start_at=count):
        # Pass args parameter as a tuple
        background_thread = Thread(target=self.add_one, args=(start_at,))
        background_thread.start()
        print("Started counting up")
        return

    def get_count(self):
        return print(self.count)

if __name__ == "__main__":

  inc = Increment()
  inc.get_count() # Yields 0
  inc.start_inc(start_at=5)
  while True:
    inc.get_count()
    time.sleep(2)

Upvotes: 3

SkippyElvis
SkippyElvis

Reputation: 100

Just like class fields, class methods need to be referred to using self.method syntax. So

    def start(self):
        background_thread = Thread(target=self.add_one)
        background_thread.start()
        print("Started counting up")
        return

Upvotes: 2

Related Questions