在Python Library的实际操作过程中,如果你对Python Library的实际操作步骤不是很了解的话,你可以通过我们的文章,对其有一个更好的了解,希望你通过我们的文章,会对你在此方面额知识有所提高。
Python 2.6.4 Standard Library 提供了 thread 和 threading 两个 Module,其中 thread 明确标明了如下文字。
The thread module has been renamed to _thread in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0; however, you should consider using the high-level threading module instead.
1. Thread
我们可以选择继承 Thread 来实现自己的线程类,或者直接像 C# Thread 那样传个函数进去。
from threading import *
def t(a, b):
print currentThread().name, a, b
Thread(ttarget= t,args= (1, 2)).start()
输出:
$ ./main.py
Thread-1 1 2
Python Library要实现自己的线程类,可以重写 __init__() 和 run() 就行了。不过一旦我们定义了 run(),我们传进去的 target 就不会自动执行了。
class MyThread(Thread):
def __init__(self, name, x):
Thread.__init__(self,namename=name)
self.x= x
def run(self):
print currentThread().name, self.x
MyThread("My", 1234).start()
输出:
$ ./main.py
My 1234
Thread 有个重要的属性 daemon,和 .NET Thread.IsBackground 是一个意思,一旦设置为 Daemon Thread,就表示是个 "后台线程"。
def test():
for i in range(10):
print currentThread().name, i
sleep(1)
t=Thread(target=test)
#t.daemon=True
t.start()
print "main over!"
输出:
$ ./main.py
非 Daemon 效果,Python Library进程等待所有前台线程退出。
Thread-1 0
main over!
Thread-1 1
Thread-1 2
Thread-1 3
Thread-1 4
Thread-1 5
Thread-1 6
Thread-1 7
Thread-1 8
Thread-1 9
$ ./main.py # IsDaemon
进程不等待后台线程。
Thread-1 0
main over!
以上文章就是对Python Library的实际应用操作步骤的介绍。
【编辑推荐】
【责任编辑:孙巧华 TEL:(010)68476606】
点赞 0