1.將啟動、終止和檢視執行緒狀態的方法封裝成類
2.宣告時傳入要啟動的方法
3.通過 start、stop 和 state 執行啟動、終止 和 檢視狀態
具體**如下↓
# encoding: utf-8
import time
import threading
import inspect
import ctypes
class
mythreadfunc
(object):
''' 手動終止執行緒的方法
'''def__init__
(self, func)
: self.mythread = threading.thread(target=func)
defstart
(self)
:print
('執行緒啟動'
) self.mythread.start(
)def
state
(self)
: status = self.mythread.is_alive(
)print
('執行緒狀態: '
.format
(status)
)return status
defstop
(self)
:print
('執行緒終止'
)try
:for i in
range(5
):self._async_raise(self.mythread.ident, systemexit)
time.sleep(1)
except exception as e:
print
(e)def
_async_raise
(self, tid, exctype)
:"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
ifnot inspect.isclass(exctype)
: exctype =
type
(exctype)
res = ctypes.pythonapi.pythreadstate_setasyncexc(tid, ctypes.py_object(exctype)
)if res ==0:
raise valueerror(
"invalid thread id"
)elif res !=1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=null to revert the effect"""
ctypes.pythonapi.pythreadstate_setasyncexc(tid,
none
)raise systemerror(
"pythreadstate_setasyncexc failed"
)if __name__ ==
'__main__'
:# 定義乙個讀秒器
defsecond_count()
: i =
0while
true
: i +=
1print
(i) time.sleep(1)
# 宣告乙個執行緒類
mythread = mythreadfunc(second_count)
# 啟動 --------------------------------------
mythread.start(
)# 等待三秒
time.sleep(3)
# 檢視執行緒狀態
mythread.state(
)# 等待三秒
time.sleep(3)
# 終止執行緒 ----------------------------------
mythread.stop(
)# 等待三秒
time.sleep(3)
# 再次檢視執行緒狀態
mythread.state(
)
Linux下執行緒的啟動 取消 終止
pragma once include include include using namespace std class cthread private pthread t m pid include thread.h int a 20 int cthread start void cthread...
caffe 執行緒封裝類
test.hpp ifndef internal thread hpp define internal thread hpp include include using boost shared ptr namespace boost class internalthread virtual int...
C thread 執行緒封裝類
思路是這樣的,寫乙個thread抽象類,有函式virtual void run 0,類中呼叫window api函式createthread 建立並啟動執行緒,所有執行緒都執行同乙個靜態函式threadfunction lpvoid param param傳遞執行緒物件的this指標 createt...