Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

multithreading - Pass keyword arguments to target function in Python threading.Thread

I want to pass named arguments to the target function, while creating a Thread object.

Following is the code that I have written:

import threading

def f(x=None, y=None):
    print x,y

t = threading.Thread(target=f, args=(x=1,y=2,))
t.start()

I get a syntax error for "x=1", in Line 6. I want to know how I can pass keyword arguments to the target function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
t = threading.Thread(target=f, kwargs={'x': 1,'y': 2})

this will pass a dictionary with the keyword arguments' names as keys and argument values as values in the dictionary. the other answer above won't work, because the "x" and "y" are undefined in that scope.

another example, this time with multiprocessing, passing both positional and keyword arguments:

the function used being:

def f(x, y, kw1=10, kw2='1'):
    pass

and then when called using multiprocessing:

p = multiprocessing.Process(target=f, args=('a1', 2,), kwargs={'kw1': 1, 'kw2': '2'})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...