异常发生时停止线程

时间:2012-03-26 12:40:50

标签: python multithreading exit terminate

我有10个主题,问题是当异常发生错误时,bye将被打印10次。

我只想打印一次,然后终止所有线程。这个问题有解决办法吗?

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()

3 个答案:

答案 0 :(得分:1)

您可以在线程中设置一个标志。在主循环中,你可以连续join()所有线程,等待它们消失,然后在设置了标志的情况下打印一条消息。

该标志甚至可能是例外的价值......

答案 1 :(得分:0)

from threading import Thread, Lock

stop = False
lock = Lock()

def printmsg(msg, threadNumber):
    global stop
    while True:
        try:
            if threadNumber in [3, 5, 7, 9]: # Something wrong happens
                raise NotImplementedError

            lock.acquire()
            if stop:
                lock.release()
                break
            print 'This is your message %s -- Thread Number: %s' % (msg, threadNumber)
            lock.release()
        except NotImplementedError:
            lock.acquire()
            if not stop:
                stop = True
                print 'Bye'
            lock.release()
            break

for i in range(0,11):
    Thread(target=printmsg, args=('Hello World', i)).start()

答案 2 :(得分:0)

尝试通过主线程连接所有子线程。并在主线上完成你的工作。

#-*-coding:utf-8-*-

from threading import Thread

def printmsg(msg,threadNumber):
    while True:
        try:
            print 'this is your message %s -- Thread Number:%s'%(msg,threadNumber)
            raise
        except:
            break

if __name__ == '__main__':
    threads = []
    for i in range(0,11):
        threads.append(Thread(target=printmsg,args=('Hello Wrold',str(i))))
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    exit('Bye')