Python 多线程装饰器

Python decorator with multithreading

我想创建一个可以让函数 运行 在其自己的线程中运行的装饰器。 而且我还想使用队列作为装饰器的 arg,这样我就可以获得函数的 return 值。 像这样:

import queue
result = queue.Queue
@thread(result)
def function(args):
    print ("Hello World!")
    return args
function("Hello Everyone!")
print (result.get())

先入为主,代码会得到这样的输出:

Hello World!

Hello Everyone!

所以我这样写代码:

def thread(resultQueue = None):
    def wrapper(function):
        def process(*args, **kwargs):
            ret = function(*args, **kwargs)
            if resultQueue : resultQueue.put(ret)
            return resultQueue
        thread = threading.Thread(target = process)
        thread.setDaemon(True)
        thread.start()
        return process
    return wrapper
a = queue.Queue()

@basic.thread(a)
def test(arg):
    print (arg)
    time.sleep(3)
    return arg[::-1]
test("Hello World!")
print ("Hello!")
print (a.get())

但是我得到了这个错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python34\lib\threading.py", line 911, in _bootstrap_inner
    self.run()
  File "C:\Python34\lib\threading.py", line 859, in run
    self._target(*self._args, **self._kwargs)
  File "test.py", line 214, in process
    ret = function(*args, **kwargs)
TypeError: test() missing 1 required positional argument: 'arg'

为什么我会遇到这个异常,我该如何解决?

谢谢!

您正在 wrapper 函数中创建新的 Thread。相反,您需要在其中定义一个新方法来创建线程。

def thread(resultQueue=None):
    def wrapper(function):
        def pw(*args, **kwargs):
            def process(*args, **kwargs):
                # print(args, kwargs)
                ret = function(*args, **kwargs)
                if resultQueue:
                    resultQueue.put(ret)
                # return resultQueue
            thread = threading.Thread(target=process, args=args, kwargs=kwargs)
            thread.setDaemon(True)
            thread.start()
            return process
        return pw
    return wrapper

并且您还需要将参数传递给 Thread 构造函数。这就是您收到错误的原因。