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
相关文档:
开发环境:Ubuntu9.10,python2.6,gcc4.4.11,ubuntu下的python运行包和开发包是分开的,因此需要在新利得里面安装python-all-dev,从而可以在代码中引用python的头文件和库。2.下面是一个最简单的可以供python调用的c扩展模块,假设c程序文件名为foo.c:代码#include <Python.h>
static PyObject* foo_b ......
myDict = { 'item1' : [ 7, 1, 9], 'item2' : [8, 2, 3], 'item3' : [ 9, 3, 11 ] }
def sortDic(Dict,valuePostion):
return sorted(Dict.items(),key=lambda e:e[1][valuePostion])
//按value的第3个值排序
sortDic(myDict,2)
[('item2', [8, 2, 3]), ('item1', [7, 1, 9]), ('item3', [9, 3, 11])]
//按value的第 ......
以下"#"开头是Ubuntu终端命令
1。首先安装Ubuntu10.04
参考 http://wiki.ubuntu.org.cn/
2。修改root用户密码
3。使用root登陆系统
4。Ubuntu默认已经安装python2.6.5
5。下载stackless
查看网址 http://zope.stackless.com/download/sdocument_view
# cd /usr/src
# wget http://www.sta ......
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 ......