【python 多线程存数据lock(锁)】

2023-11-10

多线程存数据不会数据丢失

案例一、

这里只是简单的线程池
import os
from concurrent.futures import ThreadPoolExecutor
from time import perf_counter
import time
import threading as th
 
lock=th.Lock()
 
def write(text,path='re.txt'):
    lock.acquire()
    with open(path,'a') as fp:
        fp.write(text)
    lock.release()
 
def make_test_txt(path='test_txt.txt'):
    with open(path,'w') as fp:
        for i in range(100):
            fp.write(str(i)+'\n')
 
#os.remove('re.txt')
 
make_test_txt()
with open('test_txt.txt') as fp:
    texts=fp.readlines()
print(len(texts))
 
t=perf_counter()
 
pool=ThreadPoolExecutor(max_workers=2)
pool.map(write,texts)
pool.shutdown(wait=True)
 
time.sleep(1)
with open('re.txt') as fp:
    texts2=fp.readlines()
print(len(texts2))
 
 

案例二、

import threading as th
 
lock=th.Lock()

def make_test_txt(path='test_txt.txt'):
    with open(path,'w') as fp:
        for i in range(100):
            fp.write(str(i)+'\n')

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【python 多线程存数据lock(锁)】 的相关文章

随机推荐