易截截图软件、单文件、免安装、纯绿色、仅160KB

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


相关文档:

关于Python中时间与字符串直接的转换

>>> import time
>>> import datetime
>>>
now = time.localtime()
>>> now
(2006, 4, 30, 18, 7, 35,
6, 120, 0)
>>> type(now)
<type 'time.struct_time'>
>>>
str_now = time.strftime("%m/%d/%Y %X", now )
>>>
str_n ......

Python MySQLdb 查询返回字典结构


Python MySQLdb 查询返回字典结构 smallfish
MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.DictCursor就行。
默认程序:
import MySQLdb
db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', d ......

Python为类定义“拷贝构造函数”

初学Python,这么做好像有点2,凑合能用:
class MyClass():
def __init__(self, n = 10):
self._Field = n
def __getitem__(self, range):
return MyClass(self._Field)
obj1 = MyClass()
obj2 = obj1
obj3 = obj1[:]
obj1._Field = 100
obj4 = MyClass(123)
print obj1._Field, obj2. ......

Python中的OS模块

os模块提供了多数操作系统的功能接口函数.当os模块被导入后,它会自适应于不同的操作系统平台,如posix或NT系统平台,os模块会根据不同的平台进行相应的操作.本节内容将对os模块提供的函数进行详细的解读.
1.1 文件操作函数
1.1.1 open()函数提供创建、打开、修改文件的功能。
Example 1-1. Using the os Module to Rename ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号