Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python线程无法正确执行_Python_Multithreading_Queue_Python Multithreading_Python 3.8 - Fatal编程技术网

Python线程无法正确执行

Python线程无法正确执行,python,multithreading,queue,python-multithreading,python-3.8,Python,Multithreading,Queue,Python Multithreading,Python 3.8,我有一个thread_函数(ticker),它基本上将股票符号作为字符串接收,检查它是否满足条件,如果满足条件,则将其附加到列表中投降(ticker,df)函数返回股票符号或不返回任何内容。当我循环5000多个代码并为它们提取数据时,我实现了一个线程。在没有实现线程的情况下,这段代码至少需要半个小时才能完成,但它实际上是有效的,我在结果列表的最后得到了数据。但是,线程化在不到一秒钟内完成,但结果列表最后为空。出于某种原因,当我将断点放在投降()函数上时,它从未停止过,但它进入了pull_data

我有一个thread_函数(ticker),它基本上将股票符号作为字符串接收,检查它是否满足条件,如果满足条件,则将其附加到列表中投降(ticker,df)函数返回股票符号或不返回任何内容。当我循环5000多个代码并为它们提取数据时,我实现了一个线程。在没有实现线程的情况下,这段代码至少需要半个小时才能完成,但它实际上是有效的,我在结果列表的最后得到了数据。但是,线程化在不到一秒钟内完成,但结果列表最后为空。出于某种原因,当我将断点放在投降()函数上时,它从未停止过,但它进入了pull_data()函数,该函数基本上从Yahoo Finance下载数据。代码如下:

tickers = pd.read_csv("./text_files/stock_list.csv")


def thread_function(ticker):
    try:
        df = pull_data(ticker)
        if not df.empty:
            if capitulation(ticker, df):
                results.append(ticker)
    except:
        pass

    with print_lock:
        print(threading.current_thread().name, ticker)


def threader():
    while True:
        worker = q.get()
        thread_function(worker)
        q.task_done()


print_lock = threading.Lock()

q = Queue()


# how many threads are we going to allow
for x in range(10):
    t = threading.Thread(target=threader)
    t.daemon = True
    t.start()


start = time.time()


for ticker in tickers.yahoo_symbol:
    q.put(lambda: thread_function(ticker))


q.join()

print('Entire job took:', time.time()-start)`
编辑:

我也尝试过使用多处理池和apply_async函数,如下代码所示,但它仍然不会返回正常运行时返回的列表:

def log_result(result):
if result is not None:
    results.append(result)

pool = Pool(25)
start = time.time()
for x in tickers.yahoo_symbol:
    pool.apply_async(thread_function, args=(x,), callback=log_result)
pool.close()
pool.join()

print(results)
print('Entire job took:', time.time() - start)

在这种情况下,由于多处理抛出AttributeError,thread_function()被移动到另一个文件。

当使用线程或多处理时,函数将在线程内拥有这些变量的自己副本,并且不会更新主脚本中的变量。这就是该变量为空的原因


您应该查看多处理库,特别是池和应用异步函数。这些工具允许您将其他线程的结果返回到主线程。

Hey@RobertHafner,您能检查我的编辑吗?在我按照你的建议调整代码后,它仍然不起作用。你必须从函数中收集返回值,不能从线程内部修改主脚本中的全局变量。谢谢。我试图寻找一些方法来做到这一点,但它们似乎不起作用。有什么例子吗?