OpenThread简介
OpenThread库,提供了一个Thread类,供用户创建自己的线程。其使用非常方便,用户只需要继承自OpenThreads::Thread类,然后自己重写run接口即可。
Thread程序示例
下面程序,使用一个线程,去卖票。g_ticketCounts表示当前可用的票的数量。
#include <OpenThreads/Thread>
#include <iostream>
int g_ticketCounts = 100;
class TicketSellThread : public OpenThreads::Thread
{
public:
virtual void run()
{
for (int i = 0; i < 50; i++)
{
g_ticketCounts--;
std::cout << g_ticketCounts << std::endl;
}
}
};
int main(int argc, char** argv)
{
TicketSellThread ticketSellThread1;
ticketSellThread1.start();
//等待ticketSellThread1运行完,然后再让主线程往下运行
while(ticketSellThread1.isRunning())
OpenThreads::Thread::YieldCurrentThread();
return 0;
}
线程的取消
线程的取消,是通过cancle函数来实现的。重写此函数,然后外界调用。这里通过一个bool变量,_done,来表示线程是否可以结束。主线程通过调用cancel,把_done设置为true,然后TicketSellThread判断_done的值,结束run函数的运行,从而达到取消线程的目的。
#include <OpenThreads/Thread>
#include <iostream>
int g_ticketCounts = 100;
class TicketSellThread : public OpenThreads::Thread
{
public:
TicketSellThread():_done(false){}
virtual void run()
{
for (int i = 0; i < 50; i++)
{
if (_done)
{
return;
}
g_ticketCounts--;
std::cout << g_ticketCounts << std::endl;
}
}
virtual int cancel()
{
_done = true;
return 0;
}
private:
bool _done;
};
int main(int argc, char** argv)
{
TicketSellThread ticketSellThread1;
ticketSellThread1.start();
OpenThreads::Thread::microSleep(3000); //主线程休眠一会,让ticketSellThread1运行一会
ticketSellThread1.cancel(); //取消售票线程
//等待ticketSellThread1处理完善后工作,然后再让主线程往下运行
while(ticketSellThread1.isRunning())
OpenThreads::Thread::YieldCurrentThread();
return 0;
}