创建线程函数的线程类实例

2024-09-27 17:46:46 发布

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

我有一个thread类,在其中,我想创建一个thread函数来正确地处理thread实例。有可能吗?如果有,怎么可能?你知道吗

thread类的run函数每隔x秒执行一个作业。我想创建一个线程函数来执行与run函数并行的任务。你知道吗

class Concurrent(threading.Thread):
    def __init__(self,consType, consTemp):
           # something

    def run(self):

          # make foo as a thread

    def foo (self):
          # something

如果没有,想想下面的情况,有没有可能,怎么可能?你知道吗

class Concurrent(threading.Thread):
    def __init__(self,consType, consTemp):
           # something

    def run(self):

          # make foo as a thread

def foo ():
    # something

如果不清楚,请告诉我。我会试着重新编辑


Tags: 函数runselfmakefooinitdefthread
2条回答

只需启动另一个线程。您已经知道如何创建和启动它们,所以只需编写另一个子类Threadstart()就可以了。你知道吗

run()而不是foo()更改def foo()子类的Thread。你知道吗

首先,我建议您重新考虑使用线程。在大多数情况下,在Python中应该使用multiprocessing。。这是因为Python的GIL
除非您使用的是JythonIronPython

如果我理解正确,只需在已打开的线程中打开另一个线程:

import threading


class FooThread(threading.Thread):
    def __init__(self, consType, consTemp):
        super(FooThread, self).__init__()
        self.consType = consType
        self.consTemp = consTemp

    def run(self):
        print 'FooThread - I just started'
        # here will be the implementation of the foo function


class Concurrent(threading.Thread):
    def __init__(self, consType, consTemp):
        super(Concurrent, self).__init__()
        self.consType = consType
        self.consTemp = consTemp

    def run(self):
        print 'Concurrent - I just started'
        threadFoo = FooThread('consType', 'consTemp')
        threadFoo.start()
        # do something every X seconds


if __name__ == '__main__':
    thread = Concurrent('consType', 'consTemp')
    thread.start()

程序输出为:

Concurrent - I just started
FooThread - I just started

相关问题 更多 >

    热门问题