Python内部的线程实现
在Python中的线程运行实际是受到Interpreter的控制或者说牵制的。在Interpreter的核心函数
PyObject * PyEval_EvalFrameEx
(PyFrameObject *f, int
throwflag)
我们可以看到有一个全局变量_Py_Ticker来控制着线程对Interpreter的占有的,默认是Interpreter每执行一百条指令就会释放另一个全局变量interpreter_lock.
对于每个新线程,它是怎么加入到对Interpreter的竞争中来的呢?这个问题我研究了一下。其突入点就在当thread模块在使用thread_PyThread_start_new_thread来创建和启动新线程时,新线程的启动函数就是t_bootstrap,在t_bootstrap中,他会使用到一个函数
void
PyEval_AcquireThread
(PyThreadState *tstate)
从调用这个函数开始,新运行的线程就开始了进入到争夺interpreter的行列里来了。
对应与这个函数还有一个
void
PyEval_ReleaseThread
(PyThreadState *tstate)
很清楚,一个是用来夺锁的,一个是用来放锁的。
此外,我们知道如果在一个线程中,对应与Python的Interpreter的某个指令调用,比如是函数调用指令,而这个调用的函数有是基于C module extension来实现的,而在这个函数中如果有IO或其它block型的操作的话,无疑这个线程会被block,而这个线程被block如果没有机制在让其他线程在此线程被block时切换执行的话,那这个Interpreter的performance估计就会给人骂死了,所以我们仔细看看,发现其实在python的C实现是提供了一个机制来让被block线程在block类操作之前来让出Interpreter的。
#define
Py_BEGIN_ALLOW_THREADS
#define
Py_END_ALLOW_THREADS
我下面copy一段code文件中的原话,来看看作者的解释:
/* Interface for threads.
A module that plans to do a blocking system call (or something else
that lasts a long time and doesn't touch Python data) can allow other
threads to run as follows:
...preparations here...
Py_BEGIN_ALLOW_THREADS
...blocking system call here...
Py_END_ALLOW_THREADS
...interpret result here...
The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a
{}-surrounded block.
To leave the block in the middle (e.g., with return), you must insert
a line containing Py_BLOCK_THREADS before the return, e.g.
if (...premature_exit...) {
Py_BLOCK_THREADS
PyErr_Setf
相关文档:
def
subString
(s,
length):
us = unicode(s, 'utf-8
')
gs =
us.encode('gb2312
')
n = int(length)
t = gs[:n]
while True
:
try
:
&nb ......
python cookbook
Recipe 2.5. Counting Lines in a File
,
今日发现一个新函数
enumerate
。一般情况下对一个列表或数组既要遍历索引又要遍历元素时,会这样写:
for
i
in
range
(0
,
len
(list
)):
&n ......
os模块提供了多数操作系统的功能接口函数.当os模块被导入后,它会自适应于不同的操作系统平台,如posix或NT系统平台,os模块会根据不同的平台进行相应的操作.本节内容将对os模块提供的函数进行详细的解读.
1.1 文件操作函数
1.1.1 open()函数提供创建、打开、修改文件的功能。
Example 1-1. Using the os Module to Rename ......
Python与Mysql
一、安装MySQLdb模块
使用python连接Mysql的前提,就是需要一个让python连接到Mysql的接口,这就是MySQLdb模块。
验证是否已经安装了MySQLdb:
==========================================================
d:\usr\local\Python25>python
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v ......