- 论坛徽章:
- 0
|
Normal
0
7.8 磅
0
2
false
false
false
EN-US
ZH-CN
X-NONE
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-font-kerning:1.0pt;}
Python 语法之并发
File information
2010-1-12
磁针石:xurongzhong#gmail.com
博客:
oychw.cublog.cn
参考资料:
《Python Essential Reference 4th
Edition 2009》第20章:《Threads and Concurrency》
第20章:线程和并发
413
基本概念 413
pyhon的并发程序设计 414
multiprocessing
415
进程 415
进程通信 417
进程池 424
共享数据和同步 426
管理对象 428
连接 433
杂项工具函数 434
多处理的通用建议 435
线程 436
线程对象 436
定时器对象 437
锁对象 438
RLock
438
信号量和有界信号量 439
事件 440
状态变量 441
使用锁 442
线程终止和暂停 443
工具函数 443
全局解释锁 444
线程编程 444
queue,
Queue 444
线程中使用Queue示例 445
协同程序和微线程 446
《beginning python from novice to
professional second edition 2008》
主要内容:线程、消息传递、多处理和coroutine(协同程序)。
*基本概念
进程是运行的程序,每个进程有自己的系统状态,包含了内存、打开文件列表、程序计数器(跟踪执行的指令)、存储函数本地调用变量的堆栈。
使用os或subprocess可以创建新进程,比如:os.fork(), subprocess.Popen()。子进程和父进程是相互独立执行的。
interprocess communication (IPC)进程间的通信: 最常见的形式是基于消息传递(message passing)。message是a buffer of raw bytes,通过I/O
channel比如网络socket和管道,使用原语比如send() and recv()来发送接收消息。次常用的有内存映射区:memory-mapped regions,见mmap模块。
线程有自己的控制流和执行堆栈,但是共享系统资源和数据。
并发的难点:同步和数据共享。解决的方法一般是使用互斥锁。
write_lock = Lock()
...
# Critical section
where writing occurs
write_lock.acquire()
f.write("Here's
some data.\n")
f.write("Here's
more data.\n")
...
write_lock.release()
*python的并发程序设计
Python支持消息传递和基于线程的并发程序设计。global interpreter lock (the GIL)机制实际每个时间单元只允许单个线程执行,哪怕有多个CPU。如果瓶颈在I/O,使用多线程效果不错;如果在cpu,效果则会更差。还不如使用子进程和消息传递。也经常重构为异步事件处理系统,比如中央事件循环使用select监控I/O资源和分发异步到大量的I/O handlers。asyncore和流行的第三方的Twisted (
http://twistedmatrix/com
)可以实现这点。
消息传递在python使用很广,甚至在线程中。它难于出错,减少了锁和同步原语的使用。可以扩展至网络和分布式系统。Python的高级特性比如协程序(coroutines)也使用消息传递抽象。
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/21908/showart_2147264.html |
|