为什么python中的多处理和线程都给出错误nontype对象没有属性terminate


import multiprocessing
import threading
global thread1,thread2
def main_thread():
print('here')
global thread1,thread2
k=0
while True:
k+=1
if k==10:
terminate_it()

print(f'hello world {k}')
def terminate_it():
global thread1,thread2
thread1.terminate()
thread2.terminate()
thread1.join()
thread2.join()
thread2=threading.Thread(target=main_thread).start()
thread1=multiprocessing.Process(target=main_thread).start()
thread1.terminate()

如果你运行这段代码,你将能够重现那个错误,我只是想运行一个程序,并在我想要的时候终止它。

我希望终止进程示例:

我有一个名为func1的函数

现在我开始运行它Process/threading.Thread(target=func1)

现在我想终止它,但是我不能。

您已设置

thread2=threading.Thread(target=main_thread).start()
thread1=multiprocessing.Process(target=main_thread).start()

但必须是

thread2 = threading.Thread(target=main_thread)
thread1 = multiprocessing.Process(target=main_thread)
thread2.start()
thread1.start()

,进程应该在

内运行
if __name__ == '__main__':

完整代码

import multiprocessing
import threading
import time

def main_thread():
print('here')
k = 0
while True:
k += 1
if k == 10:
break
print(f'hello world {k}')

if __name__ == '__main__':
thread2 = threading.Thread(target=main_thread)
thread1 = multiprocessing.Process(target=main_thread)
thread2.start()
thread1.start()
thread2.join()
time.sleep(0.1)
thread1.terminate()

here
hello world 1
hello world 2
hello world 3
hello world 4
hello world 5
hello world 6
hello world 7
hello world 8
hello world 9
here
hello world 1
hello world 2
hello world 3
hello world 4
hello world 5
hello world 6
hello world 7
hello world 8
hello world 9

希望这对你有帮助。快乐编码:)

相关内容

  • 没有找到相关文章

最新更新