Python 中线程部分的代码实践求教 主要是类的


import math
import time
from threading import Thread
class SquareRootCaluatotor:
    """This class spawn a separate thread to calculate a bunch of square roots ,and checks in it once a second until it finishes"""
    def __init__(self,target):
        """Turn on the calculator thread and,while waiting for it to finish,periodically monitor its progress"""
        self.result = []
        counter = self.CalculatorThread(self,target)
        print("Turning on the calculator thread")
        counter.start()
        while len(self.result)<target:
            print("%d square roots calculated so far." %len(self.result))
            time.sleep(1)
        print("calculated %s square root;the last one is sqrt(%d)=%f" %(target,len(self.results),self.result.results[-1]))
class CalculatorThread(Thread):
    """A separate thread which actually does the calculations."""
    def __init__(self,controller,target):
        """Set up this thread,including makeing it a daemon thread so that the script can
        end without waiting for this thread to finish"""
        Thread.__init__(self)
        self.controller = controller
        self.target = target
        self.setDaemon(True)
    def run(self):
        """Calculate square roots for all numbers between 1 and the target, inclusive."""
        for i in range(1,self.target+1):
            self.controller.results.append(math.sqrt(i))
    if __name__ == 'main':
        import sys
        limit = None
        if len(sys.argv) >1:
            limit = sys.argv[1]
            try:
                limit = int(limit)
            except ValueError:
                print("Usage:%s [number of square roots to calculate"
                % sys.argv[0])
        SquareRootCaluatotor(limit)

求教:1在给SquareRootCaluatotor类实例后运行,总是提示无CalculatorThread属性,请问这是为什么?

            2 这个文件的正确运行步骤是什么?我给SquareRootCaluatotor赋变量运行是否正确?

22with33
浏览 899回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python