Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stop threads when exception happen

I have 10 threads, the problem is when something wrong happens raising the exception, bye will be printed 10 times.

I just want to print it once, then terminate all the threads. Is there any solution for the problem?

from threading import Thread
def printmsg(msg,threadNumber):
    while True:
        try:
            print 'this is your message %s -- Thread Number:%s'%(msg,threadNumber)
        except:
              exit('Bye')

for i in range(0,11):
    Thread(target=printmsg,args=('Hello Wrold',str(i))).start()
like image 243
Hamoudaq Avatar asked Apr 30 '26 02:04

Hamoudaq


1 Answers

You could set a flag in the threads. n the main loop, you could join() all threads successively in order to wait until they are gone and then print a message if the flag is set.

The flag could even be the value of the exception...

like image 115
glglgl Avatar answered May 02 '26 17:05

glglgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!