Python 在参数列表上执行线程
我希望传递一个值列表,并将每个值作为独立线程传递: 例如:Python 在参数列表上执行线程,python,multithreading,argument-passing,Python,Multithreading,Argument Passing,我希望传递一个值列表,并将每个值作为独立线程传递: 例如: import time import threading list_args = [arg1, arg2, arg3, ...., argn] # Code to execute in an independent thread import time def countdown(n): while n > 0: print('T-minus', n) n -= 1 ti
import time
import threading
list_args = [arg1, arg2, arg3, ...., argn]
# Code to execute in an independent thread
import time
def countdown(n):
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(0.5)
# Create and launch a thread
t1 = threading.Thread(target=countdown, args=(arg1,))
t2 = threading.Thread(target=countdown, args=(arg2,))
.
.
.
tn = threading.Thread(target=countdown, args=(argn,))
t1.start(); t2.start(); tn.start()
快速修复
在末尾对t1
、t2
等线程调用.join()
细节
我怀疑您真正的问题是“为什么不调用countdown
”Thread.join()
方法会导致主线程等待其他线程完成执行,然后再继续。没有它,一旦主线程完成,它就会终止整个进程
在程序中,当主线程完成执行时,进程将与其所有线程一起终止,然后线程才能调用其倒计时
函数
其他问题:
时间
两次import time
import threading
list_args = [1,2,3]
def countdown(n):
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(0.5)
# Create and launch a thread
threads = []
for arg in list_args:
t = threading.Thread(target=countdown,args=(arg,))
t.start()
threads.append(t)
for thread in threads:
thread.join()
我认为这将符合您所描述的:
for a in list_args:
threading.Thread(target=countdown, args=(a,)).start()
您可以将所有线程添加到一个独立于参数数量的列表中。在主程序结束时,必须加入所有线程。否则,主线程将退出并终止所有其他线程 工作代码:
import time
import threading
# create list [0, 1, ..., 9] as argument list
list_args = range(10)
# Code to execute in an independent thread
def countdown(n):
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(0.5)
if __name__ == '__main__':
threads = []
# create threads
for arg in list_args:
threads.append(threading.Thread(target=countdown, args=(arg,)))
# start threads
for thread in threads:
print("start")
thread.start()
# join threads (let main thread wait until all other threads ended)
for thread in threads:
thread.join()
print("finished!")
回答得很好,但它不能与列表定义一起工作。是的,没错,我只是把它留在了问题中。我将把它改为我昨天测试时使用的行。谢谢你的评论,因为我不确定在循环中调用线程的能力,所以我将它保留在最接近的近似值。
import time
import threading
# create list [0, 1, ..., 9] as argument list
list_args = range(10)
# Code to execute in an independent thread
def countdown(n):
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(0.5)
if __name__ == '__main__':
threads = []
# create threads
for arg in list_args:
threads.append(threading.Thread(target=countdown, args=(arg,)))
# start threads
for thread in threads:
print("start")
thread.start()
# join threads (let main thread wait until all other threads ended)
for thread in threads:
thread.join()
print("finished!")