0

我有一个线程类,在其中,我想创建一个线程函数来正确地使用线程实例完成其工作。是否有可能,如果是,如何?

线程类的运行函数在每 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

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

4

2 回答 2

0

First of all, I suggest the you will reconsider using threads. In most cases in Python you should use multiprocessing instead.. That is because Python's GIL.
Unless you are using Jython or IronPython..

If I understood you correctly, just open another thread inside the thread you already opened:

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

The output of the program will be:

Concurrent - I just started
FooThread - I just started

于 2014-08-30T22:01:44.193 回答
0

只需启动另一个线程。您已经知道如何创建和启动它们,因此只需编写另一个子类,Thread然后start()将其与您已有的子类一起编写。

用代替更改def foo()子类。Threadrun()foo()

于 2013-04-02T14:39:15.073 回答