22

スレッドが完了したかどうかを確認するにはどうすればよいですか?次のことを試しましたが、スレッドがまだ実行されていることがわかっていても、threads_listには開始されたスレッドが含まれていません。

import thread
import threading

id1 = thread.start_new_thread(my_function, ())
#wait some time
threads_list = threading.enumerate()
# Want to know if my_function() that was called by thread id1 has returned 

def my_function()
    #do stuff
    return
4

3 に答える 3

44

重要なのは、スレッドではなくスレッドを使用してスレッドを開始することです。

t1 = threading.Thread(target=my_function, args=())
t1.start()

次に、

z = t1.is_alive()
# Changed from t1.isAlive() based on comment. I guess it would depend on your version.

また

l = threading.enumerate()

join()を使用することもできます。

t1 = threading.Thread(target=my_function, args=())
t1.start()
t1.join()
# Will only get to here once t1 has returned.
于 2013-02-25T10:05:25.713 に答える
1

を使用してスレッドを開始する必要がありますthreading

id1 = threading.Thread(target = my_function)
id1.start()

上記の時点で、言及するものがない場合はargs、空白のままにすることができます。

スレッドが生きているかどうかを確認するには、is_alive()

if id1.is_alive():
   print("Is Alive")
else:
   print("Dead")

注: Pythonのドキュメントに従って、isAlive()代わりに使用することは非推奨です。is_alive()

Pythonドキュメント

于 2020-07-21T06:48:29.560 に答える
-2

これは私のコードです、それはあなたが尋ねたものとは正確には異なりますが、多分あなたはそれが役に立つと思うでしょう

import time
import logging
import threading

def isTreadAlive():
  for t in threads:
    if t.isAlive():
      return 1
  return 0


# main loop for all object in Array 

threads = []

logging.info('**************START**************')

for object in Array:
  t= threading.Thread(target=my_function,args=(object,))
  threads.append(t)
  t.start()

flag =1
while (flag):
  time.sleep(0.5)
  flag = isTreadAlive()

logging.info('**************END**************')
于 2015-09-24T10:14:10.817 に答える