这对于WSGI应用程序来说是一个很好的python多线程模式吗?

时间:2013-02-21 15:29:29

标签: python multithreading design-patterns wsgi

这是一个很好的多线程模式吗?它有效,但它很简单,我怀疑必须有一些隐藏的陷阱。我想在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

0 个答案:

没有答案