#!/usr/bin/python
#coding=utf-8
import thread
import threading
import Queue
import time
#python中使用线程有两种方式:函数或者用类来包装线程对象
#函数方式:调用thread模块中的start_new_thread(function,args[,kwargs])函数来创建新线程
'''
参数说明
function 线程函数
agrs 传递给线程函数的参数,参数必须是个tuple类型
kwargs 可选参数
'''
#线程函数
def ptime(TfunName,delay):
count=0
while count<5:
time.sleep(delay)
count+=1
print "%s:%s"%(TfunName,time.ctime(time.time()))
#创建两个线程
try:
thread.start_new_thread(ptime,("thread 1",1))
thread.start_new_thread(ptime,("thread 2",2))
except:
print "error:unable to start thread"
while 1:
pass
#通过类创建线程
'''
python通过两个标准库thread和threading提供对线程的支持,thread提供了低级别的,原始的线程以及一个简单的锁
threading模块提供的其他方法:
threading.currentThread():返回当前线程变量
threading.enumerate():返回一个正在运行的线程list
threading.activeCount():返回正在运行的线程数量,与len(threading,enumerate())有相同的结果
除了使用方法外,线程模块提供了Thread类来处理线程,Thread类提供了以下方法:
run():用以表示线程活动的方法(线程要做的事情,意思就是线程要执行的代码)
start():启动线程活动
join([time]):等待线程结束,阻塞调用线程直到线程的join()方法被调用中止
isAlive():返回线程是否是活动的
getName():返回线程名
setName():设置线程名
'''
#使用threading模块创建线程,直接从threading.Thread继承,然后重写__init__和run方法
exitflag=0
class selfthread(threading.Thread): #继承父类threading.Thread
def __init__(self,threadid,name,count): #初始化本身和父类的构造
threading.Thread.__init__(self)
self.threadid=threadid
self.name=name
self.count=count
def run(self): #重写父类的run方法 执行的代码写到run函数里面,线程创建后会直接运行run函数
print "starting" + self.name
print_time(self.name,self.count,3)
print "exiting" + self.name
def print_time(threadName,delay,count):
while count:
if exitflag:
threading.Thread.exit()
time.sleep(delay)
print "%s:%s"%(threadName,time.ctime(time.time()))
count -=1
#创建新线程
thread1=selfthread(1,"thread1",1)
thread2=selfthread(2,"thread2",2)
thread1.start()
thread2.start()
print "exiting main thread"
'''
线程同步
使用Thread对象的Lock和Rlock可以实现简单的线程同步,两个对象都有acquire(获取锁)方法和release(释放锁)
对于那些每次都只需要一个线程操作的数据就可以放在acquire和release之间
'''
class mythread(threading.Thread):
def __init__(self,threadId,threadName,threadCounter):
threading.Thread.__init__(self) #调用父类的构造函数
self.threadId=threadId
self.threadName=threadName
self.threadCounter=threadCounter
def run(self):
print "starting" + self.threadName
#获得锁,成功获取返回true
#可选的timeout参数不填时将一直阻塞直到获取锁
#超时返回false
threadLock.acquire()
print_time(self.threadName,self.threadCounter,3)
#释放锁
threadLock.release()
def print_time(threadName,delay,counter):
while counter:
time.sleep(delay)
print "%s:%s"%(threadName,time.ctime(time.time()))
counter-=1
threadLock=threading.Lock()#创建锁对象
threads=[]
#创建新线程
thread1=mythread(1,"thread1",1)
thread2=mythread(2,"thread2",2)
#开启新线程
thread1.start()
thread2.start()
#添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
#等待所有线程完成
for t in threads:
t.join()
print "exiting main thread"
'''
python的Queue模块中提供同步的,线程安全的队列类,包括FIFO(先入先出)和LIFO(后如先出)队列还有
优先级队列PriorityQueue,这些队列都实现了锁原语,能够在线程中直接使用,可以使用队列来实现线程间的同步
Queue模块中的常用方法:
Queue.qsize()返回队列的大小
Queue.empty()如果队列为空,返回True,反之False
Queue.full()如果队列满了,返回True,反之False
Queue.get([block[;timeout]])获取队列,timeout等待时间
Queue.get_nowait()想当与Queue.get(False)
Queue.put(item)写入队列,timeout等待时间
Queue.put_nowait(item)相当于Queue.put(item,False)
Queue.task_done()在完成一项工作之后,Queue.task_done()函数向已经完成任务的队列发送一个信号
Queue.join()实际上意味着等到队列为空。再执行别的操作
'''
Flag=0
class CreatThread(threading.Thread):
def __init__(self,threadId,name,queue):
threading.Thread.__init__(self)
self.threadId=threadId
self.name=name
self.queue=queue
def run(self):
print "starting"+self.name
process_data(self.name,self.queue)
print "exiting"+self.name
def process_data(threadName,queue):
while not Flag: #当标志位为0的时候flag为flase加上not就是true,执行代码
queueLock.acquire()
if not workqueue.empty():#如果队列为空(没有数据)就释放锁让其他线程进到这个位置
data=queue.get()#获取队列中的数据
queueLock.release()
print "%s processing %s" % (threadName,data)
else:
queueLock.release()
time.sleep(1)
#定义各种对象
threadList=["thread1","thread2","thread3"]
nameList=["one","two","three","four","five"]
queueLock=threading.Lock()#创建锁对象
workqueue=Queue.Queue(10)#创建队列
threads=[]#创建线程列表
threadId=1
#创建线程
for Tname in threadList:
thread=CreatThread(threadId,Tname,workqueue)
thread.start()
threads.append(thread)#线程添加到线程列表
threadId+=1
#填充队列
queueLock.acquire()
for word in nameList:
workqueue.put(word)#向队列中写入数据
queueLock.release()
#等待队列清空
while not workqueue.empty():
pass
#队列清空后通知线程退出
Flag=1
#等待所有线程完成后释放退出,如果没有join的话主线程还没有等待其他线程完成任务就退出了,主线程一退出,整个进程就结束了
for t in threads:
t.join()
print "exit main thread"
python中多线程编程
最新推荐文章于 2025-05-27 11:16:59 发布