2009/09/13

KeyboardInterrupt (SIGINT) in multithread of Python

最近在做壓力測試,需要寫 multithread 去跑資料,遇到 ctrl-c 沒反應,問了同事後才知道 main thread 會接到這個 signal,但是仍然需要自己去 catch 這個 exception,不然仍然沒有作用。

def work():
  while not STOP:
    # jobs in worker thread

STOP = False

for n in range(num):
  workers.append(Thread(target=work))
  workers[n].start()

try:
  # jobs in main thread...
except KeyboardInterrupt:
  STOP = True

for n in range(num):
  workers[n].join()



題外話,Python multi-thread 跟 multi-process 的介面真的是簡單到一個不行,超好用的。

0 篇留言:

張貼意見