python多进程和多线程一起使用_Python3多进程与多线程区别及使用(2.线程)
threading模塊
簡述:
threading模塊
threading.currentThread(): 返回當前的線程變量。
threading.enumerate(): 返回一個包含正在運行的線程的list。正在運行指線程啟動后、結束前,不包括啟動前和終止后的線程。
threading.activeCount(): 返回正在運行的線程數量,與len(threading.enumerate())有相同的結果。
thread類
run(): 用以表示線程活動的方法。
start():啟動線程活動。
join([time]): 等待至線程中止。這阻塞調用線程直至線程的join() 方法被調用中止-正常退出或者拋出未處理的異常-或者是可選的超時發生。
isAlive(): 返回線程是否活動的。
getName(): 返回線程名。
setName(): 設置線程名。
開啟線程的兩種方式:
一:
1 from threading importThread2
3
4 defsayhi(name):5 print('%s say hello' %name)6
7
8 if __name__ == '__main__':9 t = Thread(target=sayhi, args=('hh',))10 t.start()11 print('主線程')
二:
from threading importThreadimporttimeclassSayhi(Thread):def __init__(self,name):
super().__init__()
self.name=namedefrun(self):
time.sleep(2)print('%s say hello' %self.name)if __name__ == '__main__':
t= Sayhi('hh')
t.start()print('主線程')
線程同步:
使用 Thread 對象的 Lock 和 Rlock 可以實現簡單的線程同步,這兩個對象都有 acquire 方法和 release 方法,對于那些需要每次只允許一個線程操作的數據,可以將其操作放到 acquire 和 release 方法之間。
importthreadingimporttimeclassmyThread (threading.Thread):def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID=threadID
self.name=name
self.counter=counterdefrun(self):print ("開啟線程:" +self.name)#獲取鎖,用于線程同步
threadLock.acquire()
print_time(self.name, self.counter,3)#釋放鎖,開啟下一個線程
threadLock.release()defprint_time(threadName, delay, counter):whilecounter:
time.sleep(delay)print ("%s: %s" %(threadName, time.ctime(time.time())))
counter-= 1threadLock=threading.Lock()
threads=[]#創建新線程
thread1 = myThread(1, "Thread-1", 1)
thread2= myThread(2, "Thread-2", 2)#開啟新線程
thread1.start()
thread2.start()#添加線程到線程列表
threads.append(thread1)
threads.append(thread2)#等待所有線程完成
for t inthreads:
t.join()print ("退出主線程")
線程優先級隊列( Queue)
Python 的 Queue 模塊中提供了同步的、線程安全的隊列類,包括FIFO(先入先出)隊列Queue,LIFO(后入先出)隊列LifoQueue,和優先級隊列 PriorityQueue。
這些隊列都實現了鎖原語,能夠在多線程中直接使用,可以使用隊列來實現線程間的同步。
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() 實際上意味著等到隊列為空,再執行別的操作
importqueueimportthreadingimporttime
exitFlag=0classmyThread (threading.Thread):def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID=threadID
self.name=name
self.q=qdefrun(self):print ("開啟線程:" +self.name)
process_data(self.name, self.q)print ("退出線程:" +self.name)defprocess_data(threadName, q):while notexitFlag:
queueLock.acquire()if notworkQueue.empty():
data=q.get()
queueLock.release()print ("%s processing %s" %(threadName, data))else:
queueLock.release()
time.sleep(1)
threadList= ["Thread-1", "Thread-2", "Thread-3"]
nameList= ["One", "Two", "Three", "Four", "Five"]
queueLock=threading.Lock()
workQueue= queue.Queue(10)
threads=[]
threadID= 1
#創建新線程
for tName inthreadList:
thread=myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID+= 1
#填充隊列
queueLock.acquire()for word innameList:
workQueue.put(word)
queueLock.release()#等待隊列清空
while notworkQueue.empty():pass
#通知線程是時候退出
exitFlag = 1
#等待所有線程完成
for t inthreads:
t.join()print ("退出主線程")
總結
以上是生活随笔為你收集整理的python多进程和多线程一起使用_Python3多进程与多线程区别及使用(2.线程)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 百度云文字识别 proxy
- 下一篇: python图片解析库_python用来