由于std::thread无法在运行时被其他线程强制结束, 鉴于业务需要,不得不拐弯抹角换一种新方式来实现。于是今天写了点关于这个的代码
(然而仍然存在一些问题)
class procx /** HC TECH : MutableThread Version 0.1 ( build 1 , 20160216 )*/
{
public:
procx(auto a)
{
func=a;
cancel=false;
done=false;
status_code=0;
s=nullptr;
}
~procx()
{
delete s;
}
template <typename ... ARG>
void start(ARG ... arg)
{
s=new std::thread(func,arg...);
}
void join()
{
if(s!=nullptr&&s->joinable())
{
s->join();
}
}
void detach()
{
if(s!=nullptr&&s->joinable())
{
s->detach();
}
}
bool isdone()
{
return done;
}
bool iscanceled()
{
return cancel;
}
int getcancelcode()
{
return status_code;
}
/// return: true : Thread is canceled. false: Thread is over. else will be blocked.
bool trycancel()
{
cancel=true;
join();
return done;
}
private:
void* func;
std::thread* s;
bool cancel;
bool done;
int status_code;
};
procx类就是一个线程管理的类。
如果一个线程函数希望能够被cancel,那么这个方法在编写时需要使用如下的宏定义
#define DECLX bool* doneflag,bool* cancelflag,int* _hc_status_code
#define SETUNDONE *doneflag=false;
#define SETDONE *doneflag=true;
#define CANCELPOINT(x) if(*cancelflag){*_hc_status_code=x;return;}
一个比较正规的写法如下
void proc_a(DECLX,int* ret)
{
SETUNDONE
CANCELPOINT(1);
SETDONE
}
如果整个代码能够工作,那么使用方法应该是这样的
int main()
{
int ret=0;
procx s(proc_a,&ret);
/// Start Job "s"
s.start();
/// Try to cancel Job "s"
s.trycancel();
}
然而目前还是无法通过编译,看来通过C++模板方式支持函数参数转发,变长参数这些知识我还是掌握的不太好。继续努力!