Python Library實際應用操作步驟詳解
在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的實際應用操作步驟的介紹。
【編輯推薦】