简体   繁体   中英

Python how to initialize thread with unknown number of arguments?

I'm having trouble using the starred expressions in combination with fixed argument lists when attempting to create threads.

Consider the following code:

the_queue = Queue()

def do_something(arg1, arg2, queue):
    # Do some stuff...
    result = arg1 + arg2

    queue.put(result)

def init_thread(*arguments):
    t = Thread(target=do_something, args=(arguments, the_queue))
    t.start()
    t.join()

init_thread(3,6)

This throws the exception:

TypeError: do_something() takes exactly 3 arguments (2 given)

In other words, the "arguments" tuple is evaluated as one tuple object (ie it's not unpacked), and the_queue is regarded as the second argument.

The code needs to be able to initalize threads calling different methods with an unknown number of arguments, but that always will have a "queue" parameter at the end.

Is there any way to achieve this? In that case, how? And if not -- what am I doing wrong?

Thanks.

EDIT: I should add that calling the "init_thread()" method with the queue as an argument is not an option, since I don't want the rest of my code to be "aware" of how the thread handler works internally...

你需要创建一个新的tuple

t = Thread(target = do_something, args = arguments + (the_queue, ))

You can also unpack the packed-up *arguments tuple, like so:

>>> def Print(*args):
...     print('I am prepended to every message!', *args)
... 
>>> Print('This', 'has', 'four', 'arguments')
I am prepended to every message! This has four arguments
>>> def Print(*args):
...     print('I am prepended to every message!', args)
... 
>>> Print('This', 'has', 'four', 'arguments')
I am prepended to every message! ('This', 'has', 'four', 'arguments')

So you see, referring to *agruments, as opposed to arguments, will unpack the tuple. Thus your code might be:

def init_thread(*arguments):  
    t = Thread(target=do_something, args=(*arguments, the_queue))
    t.start()
    t.join()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM