如何在while循环的每次迭代中创建一个新的Thread对象?“RuntimeError:线程只能启动一次”

How to create a new Thread object on each iteration of the while loop? 'RuntimeError: threads can only be started once'

提问人:Demeridianth 提问时间:10/29/2023 最后编辑:Solomon SlowDemeridianth 更新时间:10/29/2023 访问量:71

问:

我是线程模块的新手,所以我一直在尝试不同的简单方法来解决这个问题,但没有任何效果;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()

不起作用

python 多线程 while 循环

评论

1赞 user2357112 10/29/2023
你还记得你通常在while循环的每次迭代中做些什么吗?
0赞 Demeridianth 10/29/2023
@user2357112你能告诉我吗?
0赞 user2357112 10/29/2023
while 循环在每次迭代中运行循环体。因此,如果您希望在每次迭代中都发生一些事情,那么您将其放在哪里?
0赞 Demeridianth 10/29/2023
线程在循环中,(正如您在代码中看到的那样)问题是:您不能两次使用同一个线程;你得到:“RuntimeError:线程只能启动一次”错误
0赞 user2357112 10/29/2023
你把代码放在循环中启动线程。但是您希望在每次迭代中创建一个线程。创建线程的代码在哪里?

答:

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 的第二个和第三个代码块。