【问题标题】:twisted - run in a thread扭曲 - 在线程中运行
【发布时间】:2019-05-16 23:39:49
【问题描述】:

python 新手 初来乍到

我的团队希望我让一些现有代码在单独的线程中运行。

我想出了一个虚构的例子:

from twisted.internet import threads, reactor
from twisted.internet.defer import inlineCallbacks
from time import sleep


class SomeClass(object):
    def __init__(self):
        self.working = False

    def set_working(self, is_working):
        self.working = is_working
        print 'Flag set to {}'.format(is_working)

    @inlineCallbacks
    def do_worker_thread(self):

        # I want to make this call on the main thread
        self.set_working(True)

        # I want to do all this garbage on a separate thread and keep trucking on the main thread
        # This mimics some calls in the real code. There is a call to deferToThread and a try
        # except block there.
        def thread_proc():
            try:
                for i in range(0, 100):
                    print 'Step %d starting'.format(i)
                    self.execute_step(i)
            except Exception:
                print 'An exception happened'
        reactor.callInThread(thread_proc)

        # When the worker thread is done, I want to call back 'on_thread_work_done'

    def execute_step(self, num):
        sleep(num)
        print 'Worker thread: %d'.format(num)

    def on_thread_work_done(self):
        """I want to be called back when the worker thread is done"""
        self.set_working(False)

    @inlineCallbacks
    def do_main_thread(self):
        for c in range(ord('a'), ord('z')+1):
            sleep(c)
            print 'Main thread: {}'.format(c)


if __name__ == "__main__":
    someClass = SomeClass()
    result = someClass.do_worker_thread()
    result.addCallback(someClass.do_main_thread())

    reactor.run()

do_worker_thread 上的东西当前在主线程上运行。我在那里发表了评论,我希望它在单独的线程中运行。 do_worker_thread 立即返回很重要。

我希望输出看起来像:

Flag set to True
Step 0 starting
Main thread: a
Worker thread: 0
Worker thread: 1
Main thread: b
Worker thread: 2
Main thread: c
...

如何更改 do_worker_thread 中的内容,以便我的 set_working 调用位于主线程上,并且在工作线程完成工作之前不会设置为 False?

【问题讨论】:

    标签: python multithreading twisted


    【解决方案1】:

    试试这个。它使用callFromThread() 来调度主线程上的工作。

    from twisted.internet import threads, reactor
    from twisted.internet.defer import inlineCallbacks, returnValue
    from time import sleep
    
    
    class SomeClass(object):
        def __init__(self):
            self.working = False
    
        def set_working(self, is_working):
            self.working = is_working
            print 'Flag set to {}'.format(is_working)
    
        @inlineCallbacks
        def do_worker_thread(self):
    
            # I want to make this call on the main thread
            self.set_working(True)
    
            # I want to do all this garbage on a separate thread and keep trucking on the main thread
            # This mimics some calls in the real code. There is a call to deferToThread and a try
            # except block there.
            def thread_proc():
                try:
                    for i in xrange(0, 10):
                        print 'Step {} starting'.format(i)
                        self.execute_step(i)
                except Exception:
                    print 'An exception happened'
    
            yield threads.deferToThread(thread_proc)
    
            # When the worker thread is done, I want to call back 'on_thread_work_done'
            self.on_thread_work_done()
    
            returnValue(17)
    
        def execute_step(self, num):
            sleep(1)
            print 'Worker thread: {}'.format(num)
    
        def on_thread_work_done(self):
            """I want to be called back when the worker thread is done"""
            self.set_working(False)
    
        def do_main_thread(self):
            for i in [chr(x) for x in range(ord('a'), ord('z')+1)]:
                print 'Main thread: {}'.format(i)
                sleep(1)
    
        def thread_done(self, result):
            print 'Thread done: {}'.format(result)
    
    if __name__ == "__main__":
        someClass = SomeClass()
        # Schedule the threaded work
        result = someClass.do_worker_thread().addCallback(someClass.thread_done)
        # Schedule the main thread work
        reactor.callFromThread(someClass.do_main_thread)
        reactor.run()
    

    【讨论】:

      【解决方案2】:

      您可以使用callFromThreadblockingCallFromThread

      【讨论】:

        猜你喜欢
        • 2010-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-09
        • 1970-01-01
        • 1970-01-01
        • 2018-01-24
        • 1970-01-01
        相关资源
        最近更新 更多