- #include "stdafx.h"
- #include <iostream>
- #include "zthread/Runnable.h"
- #include "zthread/PoolExecutor.h"
- using namespace ZThread;
- using namespace std;
- class LiftOff : public Runnable
- {
- public:
- LiftOff(int count, int idn = 0): countDown(count), id(idn) {}
- ~LiftOff()
- {
- cout<< id << " competed" <<endl;
- }
- void run()
- {
- while (countDown--)
- {
- cout << id << " : " <<countDown <<endl;
- }
- cout<<"LiftOff!" <<endl;
- }
- private:
- int countDown;
- int id;
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- try
- {
- for (int i = 0; i < 5; i++)
- {
- //LiftOff a(10, i);
- //Thread t(&a );
- Thread t(new LiftOff(5,i));
- }
- cout <<"Waiting for LiftOff" <<endl;
- }
- catch (Synchronization_Exception& e)
- {
- cerr << e.what() <<endl;
- }
- cin.get();
- return 0;
- }
分配给线程的任务必须是从堆中创建的 【Thread t(new LiftOff(5,i));】,而且通过new出来的任务不需要我们管理,Thread会自己管理该任务,当该任务的引用计数为0时,自动delete该任务。
还可以看到:
for (int i = 0; i < 5; i++)
{
Thread t(new LiftOff(5,i));
}
t是在for循环里创建的局部变量,跳出此次循环后,会立即被销毁。事实上,当一个Zhread被创建时,相关联的线程就会在线程处理系统内部注册,并保持其处于活动状态,即使基于栈的Thread对象被丢弃,线程本身也会继续处于活动状态直到相关联的任务完成。