从线程函数返回值

亚当

我正在尝试从使用python的线程中运行的函数返回信息的“快照”。我认为这很容易,但是Google确实没有任何意义。

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()运行直到输入quit。一些输出示例:

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

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

穆罕默德·塔希尔(Muhammad Tahir)

您可以通过创建自定义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()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章