簡便快捷的Python開發工具介紹
Python開發工具是一個具有更高層的多線程機制接口,比如threding module,threading module是一個標準庫中的module,用Python語言實現,Python可以使用戶避免過分的語法的羈絆而將精力主要集中到所要實現的程序任務上。
我們的目標是要剖析Python開發工具中的多線程機制是如何實現的,而非學習在Python中如何進行多線程編程,所以重點會放在thread module上。通過這個module,看一看Python對操作系統的原生線程機制所做的精巧的包裝。
我們通過下面所示的thread1.py開始充滿趣味的多線程之旅,在thread module中,Python向用戶提供的多線程機制的接口其實可以說少得可憐。當然,也正因為如此,才使Python中的多線程編程變得非常的簡單而方便。我們來看看在thread module的實現文件threadmodule.c中,thread module為Python使用者提供的所有多線程機制接口。
- [thread1.py]
- import thread
- import time
- def threadProc():
- print 'sub thread id : ', thread.get_ident()
- while True:
- print "Hello from sub thread ", thread.get_ident()
- time.sleep(1)
- print 'main thread id : ', thread.get_ident()
- thread.start_new_thread(threadProc, ())
- while True:
- print "Hello from main thread ", thread.get_ident()
- time.sleep(1)
- [threadmodule.c]
- static PyMethodDef thread_methods[] = {
- {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread,…},
- {"start_new", (PyCFunction)thread_PyThread_start_new_thread, …},
- {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock, …},
- {"allocate", (PyCFunction)thread_PyThread_allocate_lock, …},
- {"exit_thread", (PyCFunction)thread_PyThread_exit_thread, …},
- {"exit", (PyCFunction)thread_PyThread_exit_thread, …},
- {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main,…},
- {"get_ident", (PyCFunction)thread_get_ident, …},
- {"stack_size", (PyCFunction)thread_stack_size, …},
- {NULL, NULL} /* sentinel */
- };
我們發現,thread module中有的接口居然以不同的形式出現了兩次,比如“start_new_thread”“start_new”,實際上在Python開發工具內部,對應的都是thread_ PyThread_start_new_thread這個函數。所以,thread module所提供的接口,真的是少得可憐。在我們的thread1.py中我們使用了其中兩個接口。關于這兩個接口的詳細介紹,請參閱Python文檔。
【編輯推薦】