[問題] python2.7 thread 相關問題

看板Python作者 (愛妳不是兩三天.......)時間14年前 (2012/01/04 03:03), 編輯推噓1(1013)
留言14則, 4人參與, 最新討論串1/1
使用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

01/04 13:11, , 1F
thread應該是自己決定什麼時候結柬, 不是由主程式去砍掉
01/04 13:11, 1F

01/04 13:39, , 2F
你這樣是 start 之後馬上 kill 掉吧
01/04 13:39, 2F

01/04 22:38, , 3F
印完他自己的ID就結束,所以是START後直接KILL,那請問要怎麼
01/04 22:38, 3F

01/04 22:39, , 4F
知道什麼時候自己結束? 像這邊我就是想要他印完就結束...
01/04 22:39, 4F

01/05 00:10, , 5F
請在主程式執行 go.join()
01/05 00:10, 5F

01/05 00:32, , 6F
原來join就是讓thread停止的方法嗎? 感謝你~~
01/05 00:32, 6F

01/05 00:33, , 7F
thread的內容跑完(print完),它就自己結束了
01/05 00:33, 7F

01/05 00:34, , 8F
go.is_alive()就可以看到False
01/05 00:34, 8F

01/05 00:35, , 9F
如果是要長時間跑的thread,要自己留出口,跑完自己就停了
01/05 00:35, 9F

01/05 00:37, , 10F
使用join()就會在run()執行完後,自己結束自己!! 3Q~~
01/05 00:37, 10F

01/05 00:38, , 11F
請問留出口是什麼意思?
01/05 00:38, 11F

01/05 09:18, , 12F
join/thread有點像是wait/process,等到child結束才return
01/05 09:18, 12F

01/05 09:20, , 13F
如果你的run()是無窮迴圈,join就永遠不會return
01/05 09:20, 13F

01/05 14:34, , 14F
原來如此..3Q~~
01/05 14:34, 14F
文章代碼(AID): #1F0r4CvR (Python)
文章代碼(AID): #1F0r4CvR (Python)