1、什麼是線程安全
線程是操做系統可以進行運算調度的最小單位。app
線程被包含在進程中,是進程中實際處理單位。一條線程就是一堆指令集合。函數
import threading import time def test1(threadName,delay): #爲線程定義一個函數 count = 0 while count < 5: time.sleep(delay) count += 1 print("進程{0},執行時間{1}".format(threadName,time.ctime(time.time()))) try: #建立兩個線程 threading._start_new_thread(test1,("thread-1",2,)) threading._start_new_thread(test1,("thread-2",4,)) except: print("Error:沒法啓動線程") while 1: pass
運行結果ui
2、實現多進程的兩種方式操作系統
一、將要執行的方法做爲參數傳遞給 Thread 的構造方法。——用類來包裝線程對象。線程
即 t = threading.Thread(target=action, args=(i,)) 其中action 指的是線程函數。orm
二、經過 繼承 的方式實現!從 Thread 繼承,並重寫run() 方法。對象
3、線程模塊經常使用的方法。繼承
一、Python3 經過兩個標準庫 _thread 和 threading 提供對線程的支持。隊列
二、threading 模塊除了包含 _thread 模塊中的全部方法外,還提供的其餘方法:
threading.currentThread(): 返回當前的線程變量
threading.enumerate(): 返回一個包含正在運行的線程的list。正在運行指線程啓動後、結束前,不包括啓動前和終止後的線程。
threading.activeCount(): 返回正在運行的線程數量,與len(threading.enumerate())有相同的結果。
三、 Thread類 方法:
3.1 run(): 用以表示線程活動的方法
3.2 start():啓動線程活動
3.3 join([time]): 等待至線程停止。這阻塞調用線程直至線程的join() 方法被調用停止-正常退出或者拋出未處理的異常-或者是可選的超時發生
3.4 isAlive(): 返回線程是否活動的
3.5 getName(): 返回線程名
3.6 setName(): 設置線程名
4、線程鎖
一、若是多個線程共同對某個數據修改,則可能出現不可預料的結果,爲了保證數據的正確性,須要對多個線程進行同步。
二、使用 Thread 對象的 Lock 和 Rlock 能夠實現簡單的線程同步,這兩個對象都有 acquire 方法和 release 方法,對於那些須要每次只容許一個線程操做的數據,能夠將其操做放到 acquire 和 release 方法之間。
三、鎖有兩種狀態——鎖定和未鎖定。
四、語法格式:經過threading.Lock()來建立鎖,函數在執行的時候先要得到鎖,執行完之後要釋放鎖。
with lock:
lock.acquire()
lock.release()
五、示例
import threading import time class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print ("開啓線程: " + self.name) # 獲取鎖,用於線程同步 threadLock.acquire() print_time(self.name, self.counter, 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, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # 開啓新線程 thread1.start() thread2.start() # 添加線程到線程列表 threads.append(thread1) threads.append(thread2) # 等待全部線程完成 for t in threads: t.join() print ("退出主線程")
運行結果
5、線程優先排隊
一、Python 的 Queue 模塊中提供了同步的、線程安全的隊列類,包括FIFO(先入先出)隊列Queue,LIFO(後入先出)隊列LifoQueue,和優先級隊列 PriorityQueue。
二、Queue 模塊中的經常使用方法:
2.1 Queue.qsize() 返回隊列的大小
2.2 Queue.empty() 若是隊列爲空,返回True,反之False
2.3 Queue.full() 若是隊列滿了,返回True,反之False
2.4 Queue.full 與 maxsize 大小對應
2.5 Queue.get([block[, timeout]])獲取隊列,timeout等待時間
2.6 Queue.get_nowait() 至關Queue.get(False)
2.7 Queue.put(item) 寫入隊列,timeout等待時間
2.8 Queue.put_nowait(item) 至關Queue.put(item, False)
2.9 Queue.task_done() 在完成一項工做以後,Queue.task_done()函數向任務已經完成的隊列發送一個信號
2.10 Queue.join() 實際上意味着等到隊列爲空,再執行別的操做
三、示例
import queue import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q def run(self): print ("開啓線程:" + self.name) process_data(self.name, self.q) print ("退出線程:" + self.name) def process_data(threadName, q): while not exitFlag: queueLock.acquire() if not workQueue.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 in threadList: thread = myThread(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 # 通知線程是時候退出 exitFlag = 1 # 等待全部線程完成 for t in threads: t.join() print ("退出主線程")
運行結果