从线程函数返回一个值

时间:2016-02-25 08:47:50

标签: python

我试图返回"快照"来自使用python在线程中运行的函数的信息。我认为这很容易,但google doesent会有任何感觉。

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()

上面的例子给了我AttributeError: 'int' object has no attribute 'count',但我尝试了一些"解决方案"不同,没有成功。

在这个例子中,我想要counter()运行,直到我进入退出状态。一点输出示例:

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

问题:

  • 如何返回"快照"价值来自def counter

  • 如果我让它运行几个小时,我会有内存问题吗?

1 个答案:

答案 0 :(得分:2)

您可以通过创建自定义Thread课程来完成此操作。但请记住,这个无限循环将耗尽运行此线程的CPU核心。

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()