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
相关文档:
>>> 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 ......
使用xlrd
来
读取,xlrd的下载及安装可以参看:
Python
"xlrd" package for extracting data from Excel files
---------------------------------------------------------------------------------
#coding=utf-8
import xlrd
import os, types, datetime
#excel存放目录
dir = u'D:\\temp\\excel'
......
开发环境: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 ......
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 ......