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 */
};
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
我们发现,thread module中有的接口居然以不同的形式出现了两次,比如“start_new_thread”“start_new”,实际上在Python开发工具内部,对应的都是thread_ PyThread_start_new_thread这个函数。所以,thread module所提供的接口,真的是少得可怜。在我们的thread1.py中我们使用了其中两个接口。关于这两个接口的详细介绍,请参阅Python文档。
【编辑推荐】