线程
一、_thread
1.参考类型:
_thread.start_new_thread ( function, args[, kwargs] )
- function - 线程函数。
- args - 传递给线程函数的参数,他必须是个tuple类型。
- kwargs - 可选参数
2.参考代码:
import _thread import time def print_time(threadNeme,delay): count=0 while count<5: time.sleep(delay) count+=1 print("%s:%s"%(threadNeme,time.time())) try: _thread.start_new_thread(print_time,('1',1,)) _thread.start_new_thread(print_time,('2',2,)) except: print_time("无法启动线程") while 1: pass
二、threading
1,功能方法:
- threading.currentThread(): 返回当前的线程变量。
- threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
- threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果
- threading.Thread
- threading._thread
2.threading.Thread 的方法
(1)功能:
- run(): 用以表示线程活动的方法。
- start():启动线程活动。
- join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
- isAlive(): 返回线程是否活动的。
- getName(): 返回线程名。
- setName(): 设置线程名。
(2)代码示例
import threading import time e=0 class myThread (threading.Thread): def __init__(self,treadid,name,counter): threading.Thread.__init__(self) self.treadid=treadid self.name=name self.counter=counter def run(self): print("开始线程:"+self.name) priny_time(self.name,self.counter,5) print("退出线程:"+self.name) def priny_time(threadname,daley,counter): while counter: if e: threadname.exit() time.sleep(daley) print("%s:%s"%(threadname,time.ctime())) counter-=1 thread1=myThread(1,"2",1) thread2=myThread(2,'4',2) thread1.start() thread2.start() thread1.join() thread2.join() print("退出主线程")
三、线程优先级队列( Queue)
(1)Queue 模块中的常用方法:
- Queue.qsize() 返回队列的大小
- Queue.empty() 如果队列为空,返回True,反之False
- Queue.full() 如果队列满了,返回True,反之False
- Queue.full 与 maxsize 大小对应
- 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() 实际上意味着等到队列为空,再执行别的操作
(2)代码
1 import queue 2 import threading 3 import time 4 5 exitFlag = 0 6 7 class myThread (threading.Thread): 8 def __init__(self, threadID, name, q): 9 threading.Thread.__init__(self) 10 self.threadID = threadID 11 self.name = name 12 self.q = q 13 def run(self): 14 print ("开启线程:" + self.name) 15 process_data(self.name, self.q) 16 print ("退出线程:" + self.name) 17 18 def process_data(threadName, q): 19 while not exitFlag: 20 queueLock.acquire() 21 if not workQueue.empty(): 22 data = q.get() 23 queueLock.release() 24 print ("%s processing %s" % (threadName, data)) 25 else: 26 queueLock.release() 27 time.sleep(1) 28 29 threadList = ["Thread-1", "Thread-2", "Thread-3"] 30 nameList = ["One", "Two", "Three", "Four", "Five"] 31 queueLock = threading.Lock() 32 workQueue = queue.Queue(10) 33 threads = [] 34 threadID = 1 35 36 # 创建新线程 37 for tName in threadList: 38 thread = myThread(threadID, tName, workQueue) 39 thread.start() 40 threads.append(thread) 41 threadID += 1 42 43 # 填充队列 44 queueLock.acquire() 45 for word in nameList: 46 workQueue.put(word) 47 queueLock.release() 48 49 # 等待队列清空 50 while not workQueue.empty(): 51 pass 52 53 # 通知线程是时候退出 54 exitFlag = 1 55 56 # 等待所有线程完成 57 for t in threads: 58 t.join() 59 print ("退出主线程")
四、线程同步
import threading import time class mythread(threading.Thread): def __init__(self,nameid,name1,counter): threading.Thread.__init__(self) self.nameid=nameid self.name1=name1 self.counter=counter def run(self): print("开始线程:"+self.name1) treadlock.acquire() fan(self.name1,self.counter,5) treadlock.release() def fan(name,date,fount): while fount: time.sleep(date) print("%s,%s"%(name,time.ctime(time.time()))) fount-=1 treadlock=threading.Lock() treads=[] tread1=mythread(1,'1:',2) tread2=mythread(2,'2:',4) tread1.start() tread2.start() treads.append(tread1) treads.append(tread2) for i in treads: i.join() print('主线程结束')