如何在扭曲的 deferToThread 中使用多个函数?
How to use multiple functions in twisted deferToThread?
根据关于扭曲的 deferToThread (http://twistedmatrix.com/documents/current/api/twisted.internet.threads.deferToThread.html) 的文档,我可以给它一个函数及其参数。
我想限制我将找到的文档的输出(比如 3 个文档),所以我也想使用 MongoDB 驱动程序 (pymongo) 的限制功能。
"find" 创建一个 PyMongo Cursor,并且不再做任何工作。 "find" 不会向 MongoDB 服务器发送消息,也不会检索任何结果。除非您像这样迭代光标,否则工作不会开始:
for doc in cursor:
print(doc)
或者:
all_docs = list(cursor)
所以你做这件事的方式已经错了:你将创建 Cursor 的工作推迟到一个线程,不需要 需要推迟,因为它不做网络 I/O。但是您随后在主线程上使用游标,您做需要推迟。
所以我提议如下:
def find_all():
# find_one() actually does network I/O
doc1 = self.mongo_pool.database[collection].find_one(self.my_id)
# creating a cursor does no I/O
cursor = self.mongo_pool.database[collection].find().limit(3)
# calling list() on a cursor does network I/O
return doc1, list(cursor)
stuff_deferred = deferToThread(find_all)
根据关于扭曲的 deferToThread (http://twistedmatrix.com/documents/current/api/twisted.internet.threads.deferToThread.html) 的文档,我可以给它一个函数及其参数。
我想限制我将找到的文档的输出(比如 3 个文档),所以我也想使用 MongoDB 驱动程序 (pymongo) 的限制功能。
"find" 创建一个 PyMongo Cursor,并且不再做任何工作。 "find" 不会向 MongoDB 服务器发送消息,也不会检索任何结果。除非您像这样迭代光标,否则工作不会开始:
for doc in cursor:
print(doc)
或者:
all_docs = list(cursor)
所以你做这件事的方式已经错了:你将创建 Cursor 的工作推迟到一个线程,不需要 需要推迟,因为它不做网络 I/O。但是您随后在主线程上使用游标,您做需要推迟。
所以我提议如下:
def find_all():
# find_one() actually does network I/O
doc1 = self.mongo_pool.database[collection].find_one(self.my_id)
# creating a cursor does no I/O
cursor = self.mongo_pool.database[collection].find().limit(3)
# calling list() on a cursor does network I/O
return doc1, list(cursor)
stuff_deferred = deferToThread(find_all)