将线程与“with”关键字结合起来

时间:2012-08-30 01:13:33

标签: python multithreading with-statement

当我运行以下程序时:

import threading
class foo(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def __enter__(self):
        print "Enter"
    def __exit__(self, type, value, traceback):
        print "Exit"

    def run():
        print "run"



if __name__ == "__main__":
    with foo() as f:
        f.start()

我将此作为输出

C:\>python test2.py
Enter
Exit
Traceback (most recent call last):
  File "test2.py", line 17, in <module>
    f.start()
AttributeError: 'NoneType' object has no attribute 'start'

有没有办法将with关键字的保证清理代码执行与线程类结合起来?

2 个答案:

答案 0 :(得分:4)

import threading
class foo(threading.Thread):
    def __enter__(self):
        print "Enter"
        return self
    def __exit__(self, type, value, traceback):
        self.join() # wait for thread finished
        print "Exit"
    def run(self):
        print "run"

if __name__ == "__main__":
    with foo() as f:
        f.start()

__enter__方法return self;这是分配给with ... as f构造中的变量的内容。

将线程加入__exit__作为suggested by @linjunhalida也是一个好主意,但不会导致您当前的问题。

如果您希望run可以使用,还应将def run(self)的定义更改为{{1}}。 :)

答案 1 :(得分:-3)

只需使用join http://docs.python.org/library/threading.html#threading.Thread.join

等待线程结束执行
import threading
class foo(threading.Thread):
    def __init__(self):
        self.thread = threading.Thread.__init__(self)
    def __enter__(self):
        print "Enter"
    def __exit__(self, type, value, traceback):
        self.thread.join() # wait for thread finished
        print "Exit"

    def run():
        print "run"



if __name__ == "__main__":
    with foo() as f:
        f.start()