爬虫日记(82):Twisted的线程返回值

Posted caimouse

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了爬虫日记(82):Twisted的线程返回值相关的知识,希望对你有一定的参考价值。

前面学习callInThread 和callFromThread函数,callInThread函数允许把一些代码交给其它线程工作,callFromThread函数允许其它线程把一些代码交给reactor线程运行。这样可以解决大部分没有返回值的函数执行,如果需要让线程执行之后还有返回值怎么呢?Twisted提供了两个函数:deferToThread 和blockingCallFromThread。

 

如果你想从一些阻塞代码里返回结果给reactor线程,就可以采用deferToThread来代替callInThread函数。下面使用例子来演示:

#爬虫日记-蔡军生(qq:9073204)

#https://mysoft.blog.csdn.net/

#2021-05-25



from __future__ import print_function

from twisted.internet import reactor, threads



import time



def doLongCalculation():

    time.sleep(3)

    return 3



def printResult(x):

    print(x)



# run method in thread and get result as defer.Deferred

d = threads.deferToThread(doLongCalculation)

d.addCallback(printResult)

reactor.run()

在这个例子里,初始化线程调用threads.deferToThread函数,把doLongCalculation函数

以上是关于爬虫日记(82):Twisted的线程返回值的主要内容,如果未能解决你的问题,请参考以下文章