2015-10-27 51 views
0

我有Python类与无限期封锁任务的方法Python的执行任务

class A(object): 
    def __init__(self): 
     # start task 

    def task(self): 
     while True: 
      #do some work 

我要开始执行任务中A.它可能会需要在自己的线程中运行的构造函数任务阻塞。如何在Python 2.7中做到这一点?

+0

您可以使用单独的工艺(https://docs.python.org/2/library/multiprocessing.html) – user996142

+0

线程可以用[线程](HTTPS来执行://docs.python .org/2.7/library/threading.html)模块。 – Kevin

回答

0

就像评论中提到的,有一个线程模块,似乎完全适合您的任务。例如:

import threading 

class A(object): 
    def __init__(self): 
     threading.Thread(target=self.task).start() 

    def task(self): 
     print 'Hello from a Thread' 

a = A() 

# output: 'Hello from a Thread'