簡(jiǎn)便快捷的Python開發(fā)工具介紹
Python開發(fā)工具是一個(gè)具有更高層的多線程機(jī)制接口,比如threding module,threading module是一個(gè)標(biāo)準(zhǔn)庫(kù)中的module,用Python語(yǔ)言實(shí)現(xiàn),Python可以使用戶避免過分的語(yǔ)法的羈絆而將精力主要集中到所要實(shí)現(xiàn)的程序任務(wù)上。
我們的目標(biāo)是要剖析Python開發(fā)工具中的多線程機(jī)制是如何實(shí)現(xiàn)的,而非學(xué)習(xí)在Python中如何進(jìn)行多線程編程,所以重點(diǎn)會(huì)放在thread module上。通過這個(gè)module,看一看Python對(duì)操作系統(tǒng)的原生線程機(jī)制所做的精巧的包裝。
我們通過下面所示的thread1.py開始充滿趣味的多線程之旅,在thread module中,Python向用戶提供的多線程機(jī)制的接口其實(shí)可以說(shuō)少得可憐。當(dāng)然,也正因?yàn)槿绱?,才?FONT size=+0>Python中的多線程編程變得非常的簡(jiǎn)單而方便。我們來(lái)看看在thread module的實(shí)現(xiàn)文件threadmodule.c中,thread module為Python使用者提供的所有多線程機(jī)制接口。
- [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 */
- };
我們發(fā)現(xiàn),thread module中有的接口居然以不同的形式出現(xiàn)了兩次,比如“start_new_thread”“start_new”,實(shí)際上在Python開發(fā)工具內(nèi)部,對(duì)應(yīng)的都是thread_ PyThread_start_new_thread這個(gè)函數(shù)。所以,thread module所提供的接口,真的是少得可憐。在我們的thread1.py中我們使用了其中兩個(gè)接口。關(guān)于這兩個(gè)接口的詳細(xì)介紹,請(qǐng)參閱Python文檔。
【編輯推薦】