如何将多重处理委托给websocket的(on_message)内部函数?

时间:2020-07-09 17:39:01

标签: python function websocket multiprocessing

我试图找到一种方法来委派我的计算机在websocket def on_message()函数的两个内部函数之间的处理能力。另外,我的代码似乎跳过了def on_message(),我不太确定是否需要在args中声明这些内部函数?

谢谢。

import websocket
import concurrent.futures as mp

Stock_stream = 'wss://data.alpaca.markets/stream'


def on_open(ws):
    print("opened")


def on_message(ws, message):
    def job():

        print("do job")
        with mp.ProcessPoolExecutor(max_workers=3) as pool:
            results = pool.map(job)
            return results

    def trade():

        print("trade")
        with mp.ProcessPoolExecutor(max_workers=1) as pool:
            results = pool.map(trade)
            return results


def on_close(ws):
    print("bye")


ws = websocket.WebSocketApp(Stock_stream, on_open=on_open, on_message=on_message, on_close=on_close)
ws.run_forever()

谢谢

1 个答案:

答案 0 :(得分:0)

据我所知, websocket-client 是一个同步库。因此,当您需要在响应之前进行长时间处理时,请使用多线程。在您的情况下,请在线程job()trade()中运行并将ws传递给它们。

...
def on_message(ws, message):

    def job(ws):
        print("do job")
        with mp.ProcessPoolExecutor(max_workers=3) as pool:
            results = pool.map(job)
            # send result to ws

    threading.Thread(target=job, args=(ws,), daemon=True).start()
...