2

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:

  • How do i return a "snapshot" value from def counter?

  • If i let this run for a couple of hours, will i have a memory issue?

3
  • I think you can't return data from thread(perhaps with some pooling things, I've read about them but not sure.). I would use subprocess module with check_output - as I know it is a good way to avoid issues with GIL that may cause longer execution. Commented Feb 25, 2016 at 8:54
  • memory issue can mean many things. If you'r referring to an overflow of the counter, this depends on how fast that while loop is. (depends on hardware) Eventually it will overflow. Commented Feb 25, 2016 at 8:59
  • @Henrik I ran a permutations script the other day, and when 50% of the execution was done, I got a warning from os x that i was out of memory. Didn't know if it was the terminal itself, or if python had an overflow. Maybe it was the terminal because the script echoed every iteration. So conclusion: I'm not really sure what i mean with memory issue =) Commented Feb 25, 2016 at 9:12

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir! very nice! I hade to add str to print(C.count + '\n'). print(str(C.count) + '\n'). Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.