您好,登錄后才能下訂單哦!
這篇文章主要介紹了Python3并發寫文件原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
使用python2在進行并發寫的時候,發現文件會亂掉,就是某一行中間會插入其他行的內容。
但是在使用python3進行并發寫的時候,無論是多進程,還是多線程,都沒有出現這個問題,難道是python3的特性嗎?
import time import os import multiprocessing from multiprocessing.dummy import Pool as ThreadPool def write(val, file): w = open(file, "a") for i in range(100): w.write("%s\n" % val) time.sleep(0.001) def thread_write(file): res, pools = [], ThreadPool(10) for i in range(10): val = str(i) * 1000 res.append(pools.apply_async(func=write, args=(val, file, ))) while res: for ret in res: if ret.ready(): res.remove(ret) time.sleep(0.01) def mutil_write(file): pools = multiprocessing.Pool(processes=10) res = [] for i in range(100): res.append(pools.apply_async(thread_write, args=(file, ))) while res: for ret in res: if ret.ready(): res.remove(ret) time.sleep(0.01) if __name__ == '__main__': file = "./write_test" mutil_write(file) with open(file) as fb: lines = 0 line_len = [] for line in fb: lines += 1 line = line.strip() line_len.append(len(line)) if len(line) != 1000: raise(Exception("error line: %s, len: %d" % (line, len(line)))) print("lines:%d, max len:%d, min:%d, avg:%.2f" % (lines, max(line_len), min(line_len), sum(line_len)/len(line_len))) os.remove(file)
上面代碼,多進程并發寫結束后,校驗每一行的長度是否是設置好的長度。用python3反復運行,均通過測試沒有異常。
$ python3 --version Python 3.7.4 $ python3 t.py lines:10000, max len:1000, min:1000, avg:1000.00
如果用python2,則會出現異常:
$ python2 --version Python 2.7.15 $ python2 t.py Traceback (most recent call last): File "t.py", line 49, in <module> raise(Exception("error line: %s, len: %d" % (line, len(line)))) Exception: error line: 333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333330000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, len: 1092
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。