Adam
Adam

Reputation: 1299

Return a value from a thread function

Im trying to return a "snapshot" of information from a function running in a thread with python. I thought it would be easy, but google doesent make any sens.

import thread
import sys
import time

def counter():
    count = 0
    while 1:
        count = count +1

# Hi screen
print('Welcome to thread example!\n')

# Avalibel commands
print('Enter [quit] to exit. enter [status] for count status')

C = thread.start_new_thread(counter ,())

while 1:
    try:
        command = raw_input('Command: ')

        if command == 'quit':
            sys.exit()
        elif command == 'status':
            print(time.ctime())
            print(C.count + '\n')
        else:
            print('unknown command. [quit] or [satus]')

    except KeyboardInterrupt:
        print "\nKeybord interrupt, exiting gracefully anyway."
        sys.exit()

This above example gives me AttributeError: 'int' object has no attribute 'count', but i have tried a few "solutions" with different no success.

In this example i want counter() to run until i enter quit. A little output example:

Welcome to thread example!

Enter [quit] to exit. enter [status] for count status
>>> Command: status
Thu Feb 25 09:42:43 2016
123567

>>> Command: status
Thu Feb 25 10:0:43 2016
5676785785768568795

Question:

Upvotes: 2

Views: 179

Answers (1)

Muhammad Tahir
Muhammad Tahir

Reputation: 5174

You can do it by creating your custom Thread class. But keep in mind this infinite loop will eat up your CPU core on which this thread will be running on.

class MyCounter(threading.Thread):
  def __init__(self, *args, **kwargs):
    super(MyCounter, self).__init__()
    self.count = 0
    self._running = True

  def run(self):
    while self._running:
      self.count += 1

  def quit(self):
    self._running = False

C = MyCounter()
C.start()

while 1:
    try:
        command = raw_input('Command: ')
        if command == 'quit':
            C.quit()
            sys.exit()
        elif command == 'status':
            print(time.ctime())
            print(C.count + '\n')
        else:
            print('unknown command. [quit] or [satus]')

    except KeyboardInterrupt:
        print "\nKeybord interrupt, exiting gracefully anyway."
        sys.exit()

Upvotes: 2

Related Questions