[上一篇 介绍了thread模块,今天来学习Python中另一个操作线程的模块:threading。threading通过对thread模块进行二次封装,提供了更方便的API来操作线程。今天内容比较多
这段时间一直在用 Python 写一个游戏的服务器程序。在编写过程中,不可避免的要用多线程来处理与客户端的交互。 Python 标准库提供了 thread 和 threading 两个模块来对多线程进行支持。其中, thread 模块以低级、原始的方式来处理和控制线程,而 threading 模块通过对 thread 进行二次封装,提供了更方便的 api 来处理线程。 虽然使用 thread 没有 threading 来的方便,但它更灵活。今天先介绍 thread 模块的基本使用, 将介绍threading 模块。
在介绍 thread 之前,先看一段代码,猜猜程序运行完成之后,在控制台上输出的结果是什么? Python
#coding=gbk
import thread, time, random
count = 0
def threadTest():
global count
for i in xrange(10000):
count += 1
for i in range(10):
thread.start_new_thread(threadTest, ())#如果对start_new_thread函数不是很了解,不要着急,马上就会讲解
time.sleep(3)
print count#count是多少呢?是10000 * 10 吗?
thread.start_new_threa