多线程值更新不一致

时间:2019-05-09 11:09:20

标签: python-3.x multithreading python-multithreading

我已经在Python 3中使用多线程编写了一个玩具示例,其中一个名为“ Sample_File”的文本文件最初包含1的整数值。

Python脚本会生成5个子线程,每个线程都获得一个锁,然后在该时间将文件的现有值加1并添加1,然后再使用该更新的值保存文件。

import time
import pickle
import threading, logging, concurrent.futures

def update_file_content(thread_name):
    '''
    A function to read an integer value from file 'Sample_File', modify it and save the updated value back to file, according to each thread
    '''

    logging.info("Starting thread: {0}".format(thread_name))

    t_lock = threading.Lock()

    with t_lock:
        logging.info("Thread {0} has acquired the lock".format(thread_name))

        # Read an integer from file to 'x'-
        with open("/Path_to_File/Sample_File", "r") as f:
            x = int(f.read())

        # Modify/update 'x'-
        x = x + 1

        # Write back updated 'x' back to file-  
        with open("/Path_to_File/Sample_File", "w") as f:
            f.write(str(x))

        logging.info("Thread {0} is releasing the lock".format(thread_name))

    logging.info("Exiting thread: {0}".format(thread_name))


if __name__ == "__main__":

    fmt = "%(asctime)s: %(message)s"

    logging.basicConfig(format=fmt, level=logging.INFO, datefmt="%H:%M:%S")

    logging.info("Main thread is now creating child threads")

    with concurrent.futures.ThreadPoolExecutor(max_workers = 5) as executor:
        for t in range(5):
            executor.submit(update_file_content, t)

    logging.info("Main thread is now exiting")

令人困惑的部分是,最后,应该在“ Sample_File”中包含的值应该为5(由于5个子线程,每个子线程都将1加上前一个值)。

但是,“ Sample_File”中的实际值为3!

此外,日志消息还显示从0到4的线程正在启​​动并获取锁。但是,只有3个线程(以随机方式)释放锁并退出(根据logging.info())

这是怎么了?

感谢您的帮助!

0 个答案:

没有答案