【发布时间】:2017-05-31 17:31:35
【问题描述】:
我意识到在这种情况下使用多处理模块会更好,但我正在使用需要几天时间才能添加模块的服务器(我不是管理员),我更愿意让它工作早点晚点。
我的代码不是线程安全的,如果可能的话,我正试图弄清楚如何使它成为线程安全的。 (下面的代码)当我不使用线程时,我本地设计的模块可以工作。
import sys, threading
from school.school_func import run_school_report
from class.class_func import run_class_report
from common.getdata import get_data #locally designed module
import pandas as pd
class myThread (threading.Thread):
def __init__(self, task, year, month, c1, c2, data):
threading.Thread.__init__(self)
self.task = task
self.year = year
self.month = month
self.class1= c1
self.class2= c2
self.data = data
def run(self):
if self.task == "school_report":
run_school_report(self.year, self.month, self.class1, self.class2, self.data)
print("\nSchool report finished! \n")
else:
run_class_report(self.year, self.month, self.class1, self.class2)
print("\nClass reports finished!\n")
#main script
YEAR = 2017
MONTH = 3
C1, C2, DATA = get_data('mysql', reload=False, blacklist=True)
t1 = myThread("school_report", YEAR, MONTH, C1, C2, DATA)
t2 = myThread("class_reports", YEAR, MONTH, C1, C2, DATA)
t1.start()
t2.start()
t1.join()
t2.join()
print("NOTICE:\nAll tasks successfully completed!\n\n")
变量 C1、C2、DATA 和为其赋值的类变量是 pandas.DataFrame 对象。
我的问题是这样的:
1) 是否有可能使这段代码线程安全?
2) 我应该硬着头皮使用多处理吗?
【问题讨论】:
-
multiprocessing是一个核心 python 模块,如果你有threading你也有multiprocessing除非你正在运行一些特殊的 python 构建,其中一些核心模块已经被特别删除?跨度> -
呵呵,很明显,我对 python 还很陌生,但看来你是对的。也许我拼错了。好尴尬。
-
不用担心,我会将评论添加为答案,以便您接受它,并且问题会在回答后关闭。
标签: python multithreading pandas multiprocessing