python模块threading实现多线程
使用threading创建多线程,创建多线程的方法:1.继承Thread类重写run方法;2.创建threading.Thread对象在他的初始化方法(__init__)
中将可调用对象作为参数传入。
#继承threading.Thread类来创建多线程。
\# coding=gbk
'''
Created on 2015年6月15日
@author: liyankun
'''
import threading, time, random
count = 0
class Counter(threading.Thread):
'''继承threading.Thread类创建多线程'''
def __init__(self, lock, threadName):
'''初始化实例对象'''
#一定要显式调用父类的初始化函数
super(Counter, self).__init__(name = threadName)
self.lock = lock
\# print self.getName() #获取线程的名字
\# self.setName(self.name+'changed') #设置线程的名字
\# print self.name
def run(self):
'''重写父类的run方法,在线程启动时,会执行该函数'''
global count
self.lock.acquire()
for i in xrange(1000):
count = count + 1
self.lock.release()
lock = threading.Lock()
for i in xrange(5):
Counter(lock, "thread-"+str(i)).start()
time.sleep(2) #保证线程都执行完毕
print count
#通过给threading.Thread对象的init()方法传递可执行对象来创建线程
import threading, time, random
count = 0
lock = threading.Lock()
def doAdd():
'''将全局变量逐一增加10000'''
global count, lock
lock.acquire()
for i in xrange(10000):
count = count + 1
lock.release()
for i in xrange(5):
threading.Thread(target = doAdd, args = (), name = 'thread-'+str(i)).start()
time.sleep(2)
print count
import threading, time, random
count = 0
lock = threading.Lock()
def doAdd():
'''将全局变量逐一增加10000'''
time.sleep(10)
global count, lock
lock.acquire()
for i in xrange(10000):
count = count + 1
lock.release()
obj = threading.Thread(target = doAdd, args = (), name = 'thread-0')
obj.start()
time.sleep(2)
print 'thread name is %s' %obj.getName() #获取线程的名称
print 'thread uuid is %d' %obj.ident
print 'thread is alive :'+ str(obj.is_alive())
print 'thread is alive :'+ str(obj.isAlive())
obj.join(4) #调用该函数将会阻塞主线程,知道被调用的线程运行结束或者超时
print 'main'
time.sleep(3)
print count
#线程间的通信–锁,threading模块有两种类型的锁1.threading.Lock()和
import threading
lock = threading.Lock()
lock.acquire()
print 'following program deadlock'
lock.acquire() #产生死锁
lock.release()
lock.release()
import threading
lock = threading.RLock()
lock.acquire() #同一线程内重复调用不会产生死锁,但是acquire()与realease()要成对存在
lock.acquire()
lock.release()
lock.release()
# threading模块中的Condition用法
# Condition类似一个锁,threading.Condition在内部维护一个锁(默认是RLock),可以在创建Condition的时候作为参数对象传入,
# 它也提供acquire()和release()方法,功能跟普通锁一样(其实内部实现也是调用Lock的对应方法)
# 以下函数在占有锁之后才能调用,否则报错
# Condition.wait([timeout]) 释放内部锁占用的锁,同时线程被挂起,知道接到通知被唤醒或者超时。重新占用锁,继续运行。
# Condition.notify() 唤醒一个线程,但不释放锁
# Condition.notify_all() 唤醒所有的锁,但不释放锁
# example:
#
# 假设有一个主人,喂养了一种兔子,主人每次给兔子喂食是要先放置容器,然后放入食物,兔子才开始吃,等兔子吃完了之后,主人在取走容器。
import threading, time
class Master(threading.Thread):
def __init__(self, con, name):
super(Master, self).__init__()
self.con = con
self.name = name
def run(self):
self.con.acquire()
print self.name + "放置喂兔子的容器"
print self.name + "向容器中投入食物"
time.sleep(1)
self.con.wait()
print self.name + "兔子吃完食物了,再次投放食物"
time.sleep(1)
self.con.notify()
self.con.wait()
print self.name + "食物吃完了,取走容器"
time.sleep(1)
self.con.release()
print self.name + "兔子喂完了"
class Rabbit(threading.Thread):
def __init__(self, con, name):
super(Rabbit, self).__init__()
self.con = con
self.name = name
def run(self):
time.sleep(1)
self.con.acquire()
print self.name + "吃食物"
print self.name + "食物吃完了,等主人再投放食物"
time.sleep(1)
self.con.notify()
self.con.wait()
print self.name + "食物吃完了,饱了"
time.sleep(1)
self.con.notify()
self.con.release()
print self.name + "去休息了"
con = threading.Condition()
master = Master(con, "master")
rabbit = Rabbit(con, "rabbit")
master.start()
rabbit.start()
# theading.Event 实现线程同步
\#coding=gbk
import threading, time
def start_notify(frame, event, ag):
print "functoin run will be called"
def end_notify(frame, event, ag):
print "function run has been run over"
class Hider(threading.Thread):
def __init__(self, cond, name):
super(Hider, self).__init__()
self.cond = cond
self.name = name
def start(self):
threading.Thread.start(self)
def run(self):
time.sleep(1)
self.cond.wait()
print self.name + ": i have to hide, come to me quickly"
self.cond.set()
time.sleep(1)
self.cond.wait()
print self.name + ": i was found"
class Seeker(threading.Thread):
def __init__(self, cond, name):
super(Seeker, self).__init__()
self.cond = cond
self.name = name
def run(self):
print self.name + ": i was in the dark"
self.cond.set()
time.sleep(1)
self.cond.wait()
print self.name + ": i found you"
self.cond.set()
print self.name + ": i win"
cond = threading.Event()
threading.settrace(start_notify)#在执行线程run方法前调用start_notify()
threading.setprofile(end_notify)#在执行线程run方法之后调用end_notify()
hider = Hider(cond, 'hider')
seeker = Seeker(cond, 'seeker')
hider.start()
seeker.start()
print "the number of running thread " + str(threading.active_count())#获取当前的线程数
print "the number of running thread " + str(threading.activeCount())
print "the entry of thread object is %s " %threading.current_thread()#获取当前线程
print "the entry of thread object is %s " %threading.currentThread()
\#列出当前所有的线程
print "the list of current running thread"
for thd in threading.enumerate():#获取当前线程列表
print thd