2012-03-26 4 views
1

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

예외를 발생시키기 위해 예제 코드에 구문 오류가 있습니까? – Fenikso

+0

내가 너를 이해하지 못한다. – Hamoudaq

+0

글쎄, 그동안 고쳐야 해. – Fenikso

답변

1

스레드에 플래그를 설정할 수 있습니다. n 메인 루프라면, 플래그가 설정되면 메시지가 출력 될 때까지 대기하기 위해 join() 모든 스레드를 연속적으로 수행 할 수 있습니다.

플래그도

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