提问人:Demeridianth 提问时间:10/29/2023 最后编辑:Solomon SlowDemeridianth 更新时间:10/29/2023 访问量:71
如何在while循环的每次迭代中创建一个新的Thread对象?“RuntimeError:线程只能启动一次”
How to create a new Thread object on each iteration of the while loop? 'RuntimeError: threads can only be started once'
问:
我是线程模块的新手,所以我一直在尝试不同的简单方法来解决这个问题,但没有任何效果;keep getting: 'RuntimeError: threads can only be started once' 错误
from threading import Thread
def task():
print('starting task..')
time.sleep(1)
print('done')
thread = Thread(target=task)
while True:
print('Fresh start')
thread.start()
thread.join()
print('Lets create a new thread for the next iteration')
.
我尝试使用RANDOM模块随机化线程的参数:
def random_number():
min_val = 1
max_val = 1000000
number = random.randint(min_val, max_val)
return number
def thread_generator():
thread1 = Thread(target=countdown, args=(10,random_number(),))
thread1.start()
不起作用
还尝试从列表中获取线程并检查它们是否正在运行 VIA is_alive:
threads = []
def thread_generator():
for n in range(1, 101):
thread = Thread(target=task, args=(10, n,))
threads.append(thread)
def new_thread():
for thread in threads:
if not thread.is_alive():
thread.start()
不起作用
答:
0赞
simon
10/29/2023
#1
您正在尝试重用相同的线程,因为您只声明了一次(在循环之外)。
您还需要通过在循环中调用构造函数来创建一个新线程:
from threading import Thread
import time
def task():
print('starting task..')
time.sleep(1)
print('done')
while True:
print('Fresh start')
thread = Thread(target=task)
thread.start()
thread.join()
print('Lets create a new thread for the next iteration')
评论
0赞
Chukwujiobi Canon
10/29/2023
也解决 OP 的第二个和第三个代码块。
评论