Skip to main content
 首页 » 编程设计

python之从线程函数返回一个值

2024年10月24日16www_RR

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

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 返回“快照”值?

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

请您参考如下方法:

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