Pickle 对象:多线程安全吗?
Pickle object : multithreading safe?
我正在使用 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
任何建议或评论将不胜感激!
是的,从多个线程或进程读取文件是安全的,只要您在线程中打开文件——即不要将相同的打开句柄传递给多个线程,这很糟糕。
请注意,由于 global interpreter lock.,如果您想并行工作,Python 中的多线程实际上可能无济于事。
我正在使用 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
任何建议或评论将不胜感激!
是的,从多个线程或进程读取文件是安全的,只要您在线程中打开文件——即不要将相同的打开句柄传递给多个线程,这很糟糕。
请注意,由于 global interpreter lock.,如果您想并行工作,Python 中的多线程实际上可能无济于事。