泡菜对象:多线程安全吗?

时间:2016-10-06 13:29:42

标签: multithreading pickle python-3.5

我正在使用Python3.5.1,带有线程模块。

我看到很多关于在几个线程中安全地写字典和Pickle文件的问题。就我而言,我想阅读它,问题是:

我可以同时多次(安全地)加载一个pickle文件吗?

伪码:

import sys    
import threading
import pickle

def function_1( pickle_file, arg_blue ):
    my_dic = pickle.load( open( pickle_file, "rb" ) )
    # process my_dic with arg_blue

def function_2( pickle_file, arg_red ):
    my_dic = pickle.load( open( pickle_file, "rb" ) )
    # process my_dic with arg_red

def main( pickle_file, arg_blue, arg_red ):
    # Using two threads to call function_1 and function_2 at the same time.
    # Function 1 and function 2 will not exchange data. Is it better to use multiprocess module ?

    # thread_blue will run function_1
    # thread_red will run function_2
    # Each of them will write in a distinct output

if __name__ == "__main__":
    main( sys.argv[1], sys.argv[2], sys.argv[3] )

调用剧本:

python3.5 my_script.py my_pickle_file.p blue red

任何建议或评论都将受到高度赞赏!

1 个答案:

答案 0 :(得分:1)

是的,从多个线程或进程读取文件是安全的,只要你在线程中打开文件 - 即不要将相同的打开句柄传递给多个线程,这是不好的。

请注意,如果由于GIL而想要并行工作,Python中的多线程可能实际上没有帮助。