首页 > 解决方案 > 多线程程序,我做的事情正确吗?任何建议或意见将不胜感激

问题描述

这是我的第一篇文章,也是我第一次尝试 Python 多线程程序,我做得对吗??我是一个初学者程序员,所以任何关于一般编码的建议或评论都值得赞赏,我在这里学习!

我想要实现的是我的函数“f_1m”完全独立于所有其他代码运行,因为这是我的数据输入并且具有最高优先级。例如,此时,当我摆动 matplotlib 图形窗口时,代码没有正确执行,并且不正确的值被传递给 pandas 数据框。我看到的是“df_1m 周期时间”在大约 100 多个周期后增加,如果这将是一个真正的并行程序,那么这不应该发生,有人能指出我正确的方向吗?

这是我的代码的一部分:...

def f_residual_work(df_1m):

    global df_2m
    global df_5m
    global df_15m
    global df_60m
    global df_results
    global df_1m_old_index

    if len(df_1m) > 0 and df_1m.index.stop > df_1m_old_index:
        df_1m_old_index = df_1m.index.stop
        # Run trading function:
        df_1m_Indicators = f_Indicators(df_1m)
        Processed = f_Alligator(df_1m_Indicators, 0, 1, 0, 0, 0, 2.4)
        df_1m_Processed = Processed[0]

        # Plot graphs
        f_plot_candle_chart(df_1m_Processed, 0, 0, '1m')

        # Update 2m, 5m etc candle chart
        results = f_xxm(df_1m, 2, df_2m, 0, 1, '2m')
        if results[0]:
            df_2m = results[1]


def f_xxm(df_1m, minutes, dataframe, plotrow, plotcolumn, dfname):

    global df_results
    update_df = False
    # check if the length of leading df_1m has updated.
    if len(df_1m) >= minutes and len(df_1m) > (len(dataframe)*minutes) and (len(df_1m) - (len(dataframe)*minutes)) == minutes:
        update_df = True
        current_time = datetime.now()
        date = current_time.strftime("%d/%m/%Y %H:%M:%S")
        new_row = {'Date': date, 'Open': df_1m['Open'][len(df_1m) - minutes],
               'High': df_1m.loc[pd.IndexSlice[len(df_1m) - minutes:len(df_1m)], 'High'].max(),
               'Low': df_1m.loc[pd.IndexSlice[len(df_1m) - minutes:len(df_1m)], 'Low'].min(),
               'Close': df_1m['Close'][len(df_1m) - 1]}
        dataframe = dataframe.append(new_row, ignore_index=True)
        # Run trading function:
        dataframe_Indicators = f_Indicators(dataframe)
        Processed = f_Alligator(dataframe_Indicators, 0, 1, 0, 0, 0, 2.4)
        dataframe_Processed = Processed[0]
        # Plot graphs adn create results df
        f_plot_candle_chart(dataframe_Processed, plotrow, plotcolumn, dfname)
        df_results[dfname] = Processed[1], Processed[2], Processed[3], Processed[4], Processed[5], Processed[6], Processed[7], Processed[8], Processed[9], Processed[10], Processed[11], Processed[12], Processed[13], Processed[14], Processed[15], Processed[16], Processed[17], Processed[18]

    return update_df, dataframe    

def f_1m(open_price, high_price, low_price ):

    global old_time_ms

    while (True):
        
        new_time_ms = int(round(time.time() * 1000))

        # Poll current tick price as long as *time* has not passed
        if (new_time_ms - old_time_ms) <= 1000:
           # Do something to gather data

        # If time has past, create output data
        elif (new_time_ms - old_time_ms) >= 1000:
            print('df_1m Cycle time:', (new_time_ms - old_time_ms), 'ms')
            old_time_ms = old_time_ms + 1000
            close_price = sellprice
            datetime_now = datetime.now()
            date_now = datetime_now.strftime("%d/%m/%Y %H:%M:%S")
            new_row = {'Date': date_now, 'Open': open_price, 'High': high_price, 'Low': low_price, 'Close': close_price}
            global df_1m
            df_1m = df_1m.append(new_row, ignore_index=True)
            # print(df_1m.tail(2))
            break

if __name__ == '__main__':

    while True:
        with concurrent.futures.ThreadPoolExecutor() as executor:

            # execute the functions
            p_1m = executor.submit(f_1m, 0, 0, 0,)
            p_Residual_work = executor.submit(f_residual_work, df_1m, )
            plt.pause(0.0001)

标签: pythonpandasmultithreadingmatplotlibparallel-processing

解决方案


推荐阅读