Boost Thread会持续更新

12 篇文章 1 订阅
3
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <boost/thread.hpp>
#include <boost/bind.hpp>
 
using  namespace  std;
using  std::tr1::shared_ptr;
 
class  Downloader
{
public :
     Downloader() : m_percent(0) {}
 
     void  start()
     {
         m_thread.reset( new  boost:: thread (boost::bind(&Downloader::download,  this )));
     }
 
     void  stop()
     {
         m_thread->interrupt();
     }
 
     int  get_percent() {  return  m_percent; }
private :
     void  download()
     {
         try
         {
             while  (m_percent < 100)
             {
                 // 这是个中断点
                 boost::this_thread::interruption_point();
                 ++m_percent;   // 模拟下载过程,加到100算结束
                 // 这里也是中断点
                 boost::this_thread::sleep(boost::posix_time::seconds(1));
             }
         }
         catch  (boost::thread_interrupted&  /*e*/ )
         {
             // 网上都说在中断点处会抛异常,但我在vs2010环境下没有捕获到
             // 以前linux下面倒是有捕获
             // 你最好还是加上try-catch吧
         }
     }
 
     shared_ptr<boost:: thread > m_thread;  // 下载进程
     int  m_percent;  // 下载百分比
};
 
int  main()
{
     cout <<  "要开始下载文件吗?"  << endl;
     char  ch;
     if  (cin >> ch && ch ==  'y' )
     {
         Downloader d;
         d.start();
         cout <<  "已经开始下载"  << endl;
         cout <<  "要停止吗?"  << endl;
         if  (cin >> ch && ch ==  'y' )
         {
             d.stop();
         }
         cout <<  "已经下载了%"  << d.get_percent() << endl;
     }
     return  0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值