zthread学习 实例四 让步、休眠、优先级

来源:互联网 发布:tomcat端口有哪些 编辑:程序博客网 时间:2024/04/30 15:58

1、让步

Thread::yield()可以介入CPU的调度,使CPU强制放弃执行当前线程。

 

2、休眠

Thread:sleep()可以使线程停止执行一段时间。

Thread:sleep()可发抛出一个Interrupted_Exception,该异常必须在run()函数中捕获,因为异常是不会跨线程传播的,只能在线程内部处理。

 

3、优先级

Thread::setPriority()、Thread::getPriority(),可以人为的改变到线程执行的优先级,确保紧急的任务先执行。

实例如下:

[cpp] view plaincopy
  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. #include <fstream>  
  4. #include "zthread/Runnable.h"  
  5. #include "zthread/Thread.h"  
  6. #include "zthread/PoolExecutor.h"    
  7. using namespace ZThread;  
  8. using namespace std;  
  9. const double pi = 3.141592653589793;  
  10. const double e = 2.718281828459;  
  11. class SimplePriorities : public Runnable  
  12. {  
  13. public:  
  14.     SimplePriorities(int idn = 0): id(idn), nCountDown(5){}  
  15.     ~SimplePriorities(){}  
  16.     friend ostream& operator << (ostream& os, const SimplePriorities& sp)  
  17.     {  
  18.         return os << "#" << sp.id << "  priority : " <<Thread().getPriority() << "count : " << sp.nCountDown <<endl;  
  19.     }  
  20.     void run()  
  21.     {  
  22.         while (true)  
  23.         {  
  24.             for (int i = 0; i < 10000; i++)  
  25.             {  
  26.                 d = d + (pi + e) /double(i);  
  27.             }  
  28.             cout << *this <<endl;  
  29.             if (--nCountDown == 0)  return;  
  30.         }  
  31.     }  
  32. private:  
  33.     int nCountDown;  
  34.     int id;  
  35.     volatile double d;  
  36. };  
  37.   
  38. int _tmain(int argc, _TCHAR* argv[])  
  39. {  
  40.     try  
  41.     {  
  42.         Thread high(new SimplePriorities);  
  43.         high.setPriority(Priority::High);  
  44.         for (int i = 1; i < 5; i++)  
  45.         {  
  46.             Thread low(new SimplePriorities(i));  
  47.             low.setPriority(Priority::Low);  
  48.         }  
  49.         cin.get();  
  50.     }  
  51.     catch (Synchronization_Exception&  e)  
  52.     {  
  53.         cerr << e.what() <<endl;  
  54.     }  
  55.     cin.get();  
  56.     return 0;  
  57. }  

 

 

0 0