一、介绍
Python通过两个标准库thread和threading提供对线程的支持。thread提供了低级别的、原始的线程以及一个简单的锁。
Thread 是threading模块中最重要的类之一,可以使用它来创建线程。有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法;直接传入要运行的方法。
Thread模块是比较底层的模块,Threading模块是对Thread做了一些包装的,可以更加方便的被使用。
另外在工作时,有时需要让多条命令并发的执行, 而不是顺序执行.
Thread模块是比较底层的模块,Threading模块是对Thread做了一些包装的,可以更加方便的被使用。
另外在工作时,有时需要让多条命令并发的执行, 而不是顺序执行.
二、代码示例
thread模块
# encoding: UTF-8
import thread
import time
# 一个用于在线程中执行的函数
def func():
for i in range(5):
print 'func'
time.sleep(1)
# 结束当前线程
# 这个方法与thread.exit_thread()等价
thread.exit() # 当func返回时,线程同样会结束
# 启动一个线程,线程立即开始运行
# 这个方法与thread.start_new_thread()等价
# 第一个参数是方法,第二个参数是方法的参数
thread.start_new(func, ()) # 方法没有参数时需要传入空tuple
# 创建一个锁(LockType,不能直接实例化)
# 这个方法与thread.allocate_lock()等价
lock = thread.allocate()
# 判断锁是锁定状态还是释放状态
print lock.locked()
# 锁通常用于控制对共享资源的访问
count = 0
# 获得锁,成功获得锁定后返回True
# 可选的timeout参数不填时将一直阻塞直到获得锁定
# 否则超时后将返回False
if lock.acquire():
count += 1
# 释放锁
lock.release()
# thread模块提供的线程都将在主线程结束后同时结束
time.sleep(6)
threading模块
继承Thread类,重写它的run方法,把线程执行的代码放进去就可以
import threading
import time
class ThreadImpl(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self._num = num
def run(self):
global total, mutex
# 打印线程名
print(threading.currentThread().getName())
for x in xrange(0, int(self._num)):
# 取得锁
mutex.acquire()
total = total + 1
# 释放锁
mutex.release()
if __name__ == '__main__':
#定义全局变量
global total, mutex
total = 0
# 创建锁
mutex = threading.Lock()
#定义线程池
threads = []
# 创建线程对象
for x in range(0, 40):
threads.append(ThreadImpl(100))
# 启动线程
for t in threads:
t.start()
# 等待子线程结束
for t in threads:
t.join()
# 打印执行结果
print(total)
直接传入要运行的方法。
# encoding: UTF-8
import threading
import time
def context(tJoin):
print 'in threadContext.'
tJoin.start()
# 将阻塞tContext直到threadJoin终止。
tJoin.join()
# tJoin终止后继续执行。
print 'out threadContext.'
def join():
print 'in threadJoin.'
time.sleep(1)
print 'out threadJoin.'
# tJoin和tContext分别为两个不同的线程
tJoin = threading.Thread(target=join)
tContext = threading.Thread(target=context, args=(tJoin,))
tContext.start()
运行结果:
in threadContext.
in threadJoin.
out threadJoin.
out threadContext.
如果想具体全面的了解python多线程,推荐一篇博客:
http://blog.csdn.net/luckytanggu/article/details/52183990