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
687 views
in Technique[技术] by (71.8m points)

multithreading - How to pass a variable by name to a Thread in Python?

Say that I have a function that looks like:

def _thread_function(arg1, arg2=None, arg3=None):
    #Random code

Now I want to create a thread using that function, and giving it arg2 but not arg3. I'm trying to this as below:

#Note: in this code block I have already set a variable called arg1 and a variable called arg2
threading.Thread(target=self._thread_function, args=(arg1, arg2=arg2), name="thread_function").start()

The above code gives me a syntax error. How do I fix it so that I can pass an argument to the thread as arg2?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Use the kwargs parameter:

threading.Thread(target=self._thread_function, args=(arg1,),
                 kwargs={'arg2':arg2}, name='thread_function').start()

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

...