import threading
import pandas as pd
import time
def get_df_1():
#set the scope of the variable to "global", meaning editing it here, it is edited globally
global df_1
# read in your xml file here (for the example I simply create some dummy data)
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df_1 = pd.DataFrame(data, columns=['Name', 'Age'])
# wait five seconds (for illustration purposes to simulate working time)
time.sleep(5)
print("df_1 fetched")
def get_df_2():
global df_2
data = [['tom', 176], ['nick', 182], ['juli', 167]]
df_2 = pd.DataFrame(data, columns=['Name', 'Height'])
time.sleep(5)
print("df_2 fetched")
df_1 = None
df_2 = None
#define threads
t1 = threading.Thread(target=get_df_1)
t2 = threading.Thread(target=get_df_2)
# start threads
t1.start()
t2.start()
#this will print immediately
print("Threads have been started")
# wait until threads finish
t1.join()
t2.join()
#this will only print after the threads are done
print("Threads have finished")
print(df_1)
print(df_2)
使用多个进程主要是因为要并行读取数据。一旦它被读入,似乎没有太多的理由让你继续两个过程。也就是说,您的进程应该读取数据,然后终止并让主进程继续
不过,我建议使用
multi-threading
而不是multi-processing
。这些差异并不总是显而易见的,但是multi-threading
将使在主线程和子线程之间共享全局变量变得更简单(我将在下面解释这一点)。多线程的另一个优点是,如果单个线程失败,它不会导致整个应用程序崩溃。多处理的情况并非如此。更多信息请参见:http://net-informations.com/python/iq/multi.htm要习惯Python中的并行工作方式需要一些时间,您必须注意的一个主要问题是如何确保您所做的工作是线程安全的。通常,用于在线程之间传递数据的机制是队列。这样可以确保在任何给定时间只有一个线程访问同一对象
也就是说,在您的简单示例中,您可以简单地定义两个全局变量并启动两个线程,每个线程将数据读入这些全局变量中的一个(即,不在线程之间共享变量)。您还必须告诉主线程等到两个线程都完成后再继续,否则主线程可能会在子线程仍在处理数据时尝试访问这些数据(同样,通常您会采用基于队列的策略来避免此问题,但这里不一定需要这样做)
下面是一些示例代码:
相关问题 更多 >
编程相关推荐