3

这是一个好的多线程模式吗?它有效,但它是如此简单,以至于我怀疑一定有一些隐藏的陷阱。我想在 WSGI 应用程序中使用它来获取异步 URL。

我受到GAE Asynchronous Requests的启发。

import datetime
import time
import threading

start_time = datetime.datetime.now()

def func(value):
    print 'START: {} {}'.format(value, datetime.datetime.now())
    time.sleep(5)
    print 'END: {} {}'.format(value, datetime.datetime.now())
    return str(value) * 10


class MyThread(threading.Thread):
    def __init__(self, func, args=(), kwargs={}):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args
        self.kwargs = kwargs
        self.result = None

    def run(self):
        self.result = self.func(*self.args, **self.kwargs)

    def get_result(self):
        self.join()
        return self.result

def run_async(*args, **kwargs):
    t = MyThread(*args, **kwargs)
    t.start()
    return t

# This will be called inside WSGI request handler only:

t1 = run_async(func=func, args=(1,))
t2 = run_async(func=func, args=(2,))
t3 = run_async(func=func, args=(3,))

print '\n'
print 'Do other stuff...'
print '\n'

print t1.get_result()
print t2.get_result()
print t3.get_result()

print '=' * 70
print 'Duration: {}'.format(datetime.datetime.now() - start_time)

输出是:

START: 1 2013-02-21 16:15:51.918112
START: 2 2013-02-21 16:15:51.918642
START: 3 2013-02-21 16:15:51.919138


Do other stuff...


END: 1 2013-02-21 16:15:56.918900
1111111111
END: 2 2013-02-21 16:15:56.924068
2222222222
END: 3 2013-02-21 16:15:56.924465
3333333333
4

0 回答 0