多子类中的Python线程

2024-09-29 01:38:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列以串行和并行方式继承自的类,如果可能,我需要对所有类使用Python线程。下面是一个例子。问题是Build类没有执行run函数,而run函数是Thread类中的一个方法。线程在MyThread类中运行良好。你知道如何让构建类以线程的形式开始吗?你知道吗

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...')`

Tags: runinbuildselffortimeinitdef
1条回答
网友
1楼 · 发布于 2024-09-29 01:38:16

仅供参考:实现所需功能的更好方法不是将threading.Thread子类化,而是生成类实例Callable,并将它们传递给Thread类的构造函数的target关键字arg。这样做的好处是可以向每个线程实例传递额外的参数。你知道吗

使用示例代码。你知道吗

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

相关问题 更多 >