Python-多執行緒寫入同一檔案
阿新 • • 發佈:2021-07-22
多執行緒
多執行緒
多執行緒寫入到一個檔案內 實現方式: 採用 concurrent 和 threading.lock 鎖的方式 採用threading 模組和 queue的方式 方案01 Executor.submit(fn, *args, **kwargs) submit返回一個Future物件。 其中future.result()的 result方法的作用是拿到呼叫返回的結果。如果沒有執行完畢就會去等待。 這裡我們使用with操作符, 使得當任務執行完成之後,自動執行shutdown函式,而無需編寫相關釋放程式碼 Executor.map(fn, *args, **kwargs) map(func, *iterables, timeout=None) iterables:可以是一個能迭代的物件. 回撥函式
程式碼示例
from concurrent.futures import ThreadPoolExecutor, as_completed from threading import Lock import random from time import time def judge_interval(n): """ # 多輸入引數時,可以將輸入組裝成list,巢狀的list的方式提取輸入引數 """ if n > 25: raise Exception('Big> 25, now %s \n' % n) elif 10 <= n <= 25: return n*1000 else: return -n def multi_thread(input_nums, input_file): """ 多執行緒寫入到一個檔案內""" lock = Lock() with open(input_file, 'a') as input_file_obj: with ThreadPoolExecutor(max_workers=3) as executor: future_jobs = {executor.submit(judge_interval, num): num for num in input_nums} for job in as_completed(future_jobs): try: # result() 方法可以獲取任務的返回值 data = job.result() # 獲取程式的輸入 data_input = future_jobs[job] print(data_input, data) with lock: input_file_obj.write('input: %s output: %s.\n' % (data_input, data)) except Exception as e: input_file_obj.write(str(e)) if __name__ == '__main__': start_time = time() log_file = r'C:\Users\ow\out.txt' nums = [random.randint(0, 40) for _ in range(0, 5)] multi_thread(nums, log_file) end_time = time() duration_time = (end_time-start_time) print(f"用時 {duration_time}秒")
參考
詳解python中的Lock與RLock https://blog.csdn.net/lgyfhk/article/details/105254079
https://www.zhihu.com/question/37732728/answer/1079020249