爲什麼這個python高速公路示例代碼使用yield sleep(1)
而不是簡單的sleep(1)
?爲什麼這個python autobahn代碼需要使用'yield'關鍵字?
class Component(ApplicationSession):
"""
An application component that publishes an event every second.
"""
@inlineCallbacks
def onJoin(self, details):
print("session attached")
counter = 0
while True:
print(".")
self.publish('com.myapp.topic1', counter)
counter += 1
yield sleep(1)
if __name__ == '__main__':
from autobahn.twisted.wamp import ApplicationRunner
runner = ApplicationRunner("ws://127.0.0.1:8080/ws", "realm1")
runner.run(Component)
謝謝。我認爲你得到了正確的答案。改變了我對答案的選擇。但這是可怕的。我怎麼知道我的其他Python代碼不會阻止Twister? – user781486 2015-02-06 12:38:11
你必須知道Python標準庫的哪些部分正在屏蔽系統調用。從本質上講,stdlib中與網絡有關的所有東西都是阻塞的。 – oberstet 2015-02-06 13:52:20