繁体   English   中英

多个子类中的Python线程

[英]Python threading in multi subclasses

我有一系列从系列中并行继承的类,如果可能,我需要对所有类使用Python线程。 下面是一个示例。 问题是Build类无法执行其运行函数,而该函数是Thread类中的一种方法。 线程在MyThread类中工作正常。 知道如何使Build类作为线程启动吗?

from threading import Thread
from random import randint
import time

class Build(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):    
        # This run function currently not being executed 
        for i in range(20):
            print('Second series %i in thread' % (i))
            time.sleep(1)

class MyThread(Build, Thread):

    def __init__(self, val):
        ''' Constructor. '''
        Thread.__init__(self)
        Build.__init__(self)

        self.val = val


    def run(self):
        for i in range(1, self.val):
            print('Value %d in thread %s' % (i, self.getName()))

            # Sleep for random time between 1 ~ 3 second
            secondsToSleep = randint(1, 5)
            print('%s sleeping fo %d seconds...' % (self.getName(), secondsToSleep))
            time.sleep(secondsToSleep)


# Run following code when the program starts
if __name__ == '__main__':
    # Declare objects of MyThread class
    myThreadOb1 = MyThread(4)
    myThreadOb1.setName('Thread 1')

    myThreadOb2 = MyThread(4)
    myThreadOb2.setName('Thread 2')

    # Start running the threads!
    myThreadOb1.start()
    myThreadOb2.start()

    # Wait for the threads to finish...
    myThreadOb1.join()
    myThreadOb2.join()

    print('Main Terminating...')`

仅供参考:代替子类threading.Thread ,实现所需目标的更好方法是使您的类实例Callable ,并将它们传递给Thread类的构造函数的target关键字arg。 这样做的好处是您可以将其他参数传递给每个Thread实例。

与您的示例代码一起。

class MyThread(Build):

    def __init__(self):
        ''' Constructor. '''
        Build.__init__(self)

        self.val = val

    # this allows your class to be a callable.
    def __call__(self, val):
        for i in range(1, val):
            print('Value %d in thread %s' % (i, self.getName()))

            # Sleep for random time between 1 ~ 3 second
            secondsToSleep = randint(1, 5)
            print('%s sleeping fo %d seconds...' % (self.getName(), secondsToSleep))
            time.sleep(secondsToSleep)

# Run following code when the program starts
if __name__ == '__main__':
    # Declare objects of MyThread class
    myThreadObj1 = MyThread()
    myThread1 = Thread(target=myThreadOb1, args=(4))
    myThread1.start()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM