python之多執行緒(學習)

小0k發表於2020-10-11

執行緒分為:

核心執行緒:由作業系統核心建立和撤銷
使用者執行緒:不需要核心支援而在使用者程式中實現的執行緒

python3 執行緒中常用的兩個模組:

_thread和threading(推薦使用)
python中使用執行緒有兩種方式:函式或者用類來包裝執行緒物件

函式式:

#呼叫模組
import _thread
import time

#為執行緒定義一個函式
def print_time(th,delay):
    count = 0
    while count < 5:
    	#延時
        time.sleep(delay)
        count += 1
        #轉換時間戳
        print("%s:%s"% (th,time.ctime(time.time())))

#建立兩個執行緒
try:
    _thread.start_new_thread(print_time,("thread1",2,))
    _thread.start_new_thread(print_time,("thread2",4,))
except:
    print("無法啟動")
#一直迴圈
while 1:
    pass

使用 threading 模組建立執行緒:

#呼叫模組
import threading
import time

exitFlag = 0
#宣告瞭個類
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)
        print_time(self.name, self.counter, 5)
        print ("退出執行緒:" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

# 建立新執行緒
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# 開啟新執行緒
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("退出主執行緒")

執行緒同步:

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 ("退出主執行緒")

相關文章