下面的例子创建了一个新的线程并使其运行,同时阻塞主进程,直到新县城完成任务为止。
#include <OpenThreads/Thread>
#include <OpenThreads/Block>
#include <iostream>
class TestThread:public OpenThreads::Thread
{
public:
TestThread()
{
_done = false ;
_count = 0 ;
}
~TestThread()
{
cancel() ;
}
void block()
{
_operator.block() ;
}
//重写终止线程函数
virtual int cancel()
{
_operator.release() ;
_done = true ;
while (isRunning())
{
OpenThreads::Thread::YieldCurrentThread() ;//出让cpu的控制权
}
return 0 ;
}
virtual void run() //重写
{
do
{
std::cout<<"("<<_count<<")" ;
++_count ;
if (_count == 10)
{
_operator.release() ;//释放当前线程
_operator.reset() ;
_operator.block() ;
}
microSleep(150000L) ;
} while (!_done);
}
protected:
bool _done ;
unsigned long _count ;
OpenThreads::Block _operator ;
};
int main()
{
TestThread t ;
t.start() ;
t.block() ;
std::cout<<"(Main"<<std::endl ;
t.cancel() ;
return 0 ;
}