看板 Python 關於我們 聯絡資訊
使用python2.7寫一個簡單的thread程式,印出當前thread的id然後結束 code: ----------------------------------------------------- from threading import Thread class t(Thread): def __init__(self): Thread.__init__(self) def run(self): self.tid = Thread.get_ident() print 'thread id is',self.tid def kill(self): 請問這邊該怎麼寫? 譬如exit(self.tid)嗎 if __name__ == "__main__" go = t() go.start() go.kill() ----------------------------------------------------- 但是一直沒辦法call get_ident() 好像不支援? 再者kill thread 能用指定id的方式殺掉嗎? 我知道可以使用SystemExit()不指定 但是這樣好像會全部都關掉 我希望可以指定thread id關閉 請問code該怎麼修正才正確呢? 謝謝~~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.167.25.215
kdjf:thread應該是自己決定什麼時候結柬, 不是由主程式去砍掉 01/04 13:11
legnaleurc:你這樣是 start 之後馬上 kill 掉吧 01/04 13:39
fcapba:印完他自己的ID就結束,所以是START後直接KILL,那請問要怎麼 01/04 22:38
fcapba:知道什麼時候自己結束? 像這邊我就是想要他印完就結束... 01/04 22:39
jlhc:請在主程式執行 go.join() 01/05 00:10
fcapba:原來join就是讓thread停止的方法嗎? 感謝你~~ 01/05 00:32
kdjf:thread的內容跑完(print完),它就自己結束了 01/05 00:33
kdjf:go.is_alive()就可以看到False 01/05 00:34
kdjf:如果是要長時間跑的thread,要自己留出口,跑完自己就停了 01/05 00:35
fcapba:使用join()就會在run()執行完後,自己結束自己!! 3Q~~ 01/05 00:37
fcapba:請問留出口是什麼意思? 01/05 00:38
kdjf:join/thread有點像是wait/process,等到child結束才return 01/05 09:18
kdjf:如果你的run()是無窮迴圈,join就永遠不會return 01/05 09:20
fcapba:原來如此..3Q~~ 01/05 14:34