계산을 비동기 적으로 수행하는 경우 지연을 사용하십시오.
다른 방법으로는 별도의 스레드에서 오랜 계산을 할 수 있습니다. deferrToThread()는 reactor.callFromThread()를 사용합니다.
(주 루프에서는 무거운 계산을하지 않는다고 가정합니다.) 작은 예 :
def some_long_foo(data_array, protocol):
def send_msg(msg, protocol):
# It actually looks petter in classes without pushing protocol here and
# there
protocol.transport.write(msg)
for n, chunk in enumerate(data_array):
do_something_cool(chunk)
if n and (n % 10 == 0):
from twisted.internet import reactor
# here send_msg will be safely executed in main reactor loop
reactor.callFromThread(send_msg, '10 more chunks processed',
protocol)
# Somwhere in lineReceived we start long calculation
def cb(result):
self.transport.write('got result: {}'.format(result))
d = threads.deferToThread(some_long_foo, data_array, self)
d.addCallback(cb)
따라서 이제 우리는 모든 데이터 (10 개) 덩어리 처리에 대해 클라이언트를 알려드립니다 다음 마지막으로 그 결과를 보냅니다. 코드가 정확하지 않을 수 있습니다.
docs
는 UPD : 단지 설명을위한 : 는 sendLine 부분을 놓쳤다. 일반적으로 문제가되지 않습니다. transport.write()
'reactor.callInThread'를 사용할 때만 별도의 스레드에서 실행되는 함수/메소드임을 명심하십시오. 콜백 및 오류도 발생합니다. 모든 것은 기본적으로 원자로 실에서 작동합니다. 코드에서 누가 - 호출 - 사람 관계를 설명하는 것이 도움이 될 수 있습니다. – wberry
서버를 "주도권을 잡으세요": Skynet의 모든 것들이 어떻게 시작 되었습니까? – tsimbalar