yingshangyue
yingshangyue
2020-08-08 18:39
采纳率: 60%
浏览 252

为什么python使用线程池会丢失部分数据?

图片说明
图片说明

如题,使用线程池会使结果行数减少,这是为什么?应该怎么修改?
图片说明

改动后还是会出现问题图片说明

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • soar3033
    soar3033 2020-08-08 20:14
    已采纳
    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))
    
    
    
    点赞 评论

相关推荐