1、让步
Thread::yield()可以介入CPU的调度,使CPU强制放弃执行当前线程。
2、休眠
Thread:sleep()可以使线程停止执行一段时间。
Thread:sleep()可发抛出一个Interrupted_Exception,该异常必须在run()函数中捕获,因为异常是不会跨线程传播的,只能在线程内部处理。
3、优先级
Thread::setPriority()、Thread::getPriority(),可以人为的改变到线程执行的优先级,确保紧急的任务先执行。
实例如下:
- #include "stdafx.h"
- #include <iostream>
- #include <fstream>
- #include "zthread/Runnable.h"
- #include "zthread/Thread.h"
- #include "zthread/PoolExecutor.h"
- using namespace ZThread;
- using namespace std;
- const double pi = 3.141592653589793;
- const double e = 2.718281828459;
- class SimplePriorities : public Runnable
- {
- public:
- SimplePriorities(int idn = 0): id(idn), nCountDown(5){}
- ~SimplePriorities(){}
- friend ostream& operator << (ostream& os, const SimplePriorities& sp)
- {
- return os << "#" << sp.id << " priority : " <<Thread().getPriority() << "count : " << sp.nCountDown <<endl;
- }
- void run()
- {
- while (true)
- {
- for (int i = 0; i < 10000; i++)
- {
- d = d + (pi + e) /double(i);
- }
- cout << *this <<endl;
- if (--nCountDown == 0) return;
- }
- }
- private:
- int nCountDown;
- int id;
- volatile double d;
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- try
- {
- Thread high(new SimplePriorities);
- high.setPriority(Priority::High);
- for (int i = 1; i < 5; i++)
- {
- Thread low(new SimplePriorities(i));
- low.setPriority(Priority::Low);
- }
- cin.get();
- }
- catch (Synchronization_Exception& e)
- {
- cerr << e.what() <<endl;
- }
- cin.get();
- return 0;
- }