【python3】多執行緒-執行緒同步
阿新 • • 發佈:2018-11-20
-
1. 認識執行緒同步現象:
在https://blog.csdn.net/weixin_41827162/article/details/84104421執行緒非同步中,
將方法1中:
建多個執行緒,同時執行多個執行緒,由新到舊逐個釋放執行緒
改成:
建立一個執行緒,執行一個執行緒,釋放一個執行緒
-
#!/usr/bin/python3 # 執行緒非同步 import threading import time exitFlag = 0 class myThread(threading.Thread): def __init__(self, thread_id, name, counter): threading.Thread.__init__(self) self.thread_id = thread_id self.name = name self.counter = counter pass def run(self): print("開始執行緒=" + self.name) run_def(self.name, self.counter, 5) print("退出執行緒=" + self.name) pass pass def run_def(thread_name, delay, counter): while counter: if exitFlag: thread_name.exit() pass time.sleep(delay) # time.sleep(0) list(thread_name) counter -= 1 pass pass def list(thread_name): print("\n執行執行緒=" + thread_name) pass threads = [] # 儲存線上執行緒 # 建立執行緒 for this_t in range(1, 10): t = myThread(this_t, "Thread-" + str(this_t), 0.1) t.start() t.join() # 執行緒同步,執行緒非同步 threads.append(t) pass # 終止執行緒 # for t in threads: # t.join() # pass print("程式完成!!")
-
2. 真正的執行緒同步:
#!/usr/bin/python3 # 執行緒同步 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(0) print("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 threadLock = threading.Lock() threads = [] for cal in range(1, 100): that = myThread(cal, "Thread-" + str(cal), cal).start() print("建立了執行緒=" + str(cal)) threads.append(that) pass print("退出主執行緒")
-