Home / Downloads / Base libraries / Help
Example how to use Thread Pool
#include
#include "traccess.h"
#include "thread.h"
#include <list>
#include <stdio.h>
class processing_task
{
public:
processing_task(int id) : _id(id) {}
processing_task(const processing_task& src) : _id(src._id) {}
void process() { _id = -_id; }
private:
int _id;
};
class test_thread_client : public terimber_thread_client
{
public:
test_thread_client(size_t count) : _count(count)
{
terimber_thread_pool_access factory;
_pool = factory.get_thread_pool(_count, 10000); // 10 sec keep in pool
_pool->borrow_thread(0, this, 100); // 100 msec and return back to pool
}
~test_thread_client()
{
_pool->revoke_client(this);
{
// before we dead we need to stop all threads
terimber::mutex_keeper keeper(_mtx_queue);
_before_processing.clear();
}
// wait until all thread closed
::Sleep(1000);
// we must destroy pool here
delete _pool;
}
// until function returns true - follow function will be called immediately
virtual bool v_thread_required(size_t ident)
{
mutex_keeper keeper(_mtx_queue);
return !_before_processing.empty();
}
// real job should be done inside this function called in separate thread
virtual void v_do_real_job(size_t ident)
{
mutex_keeper keeper(_mtx_queue);
if (_before_processing.empty())
return;
processing_task& task = _before_processing.front();
task.process();
_after_processing.push_back(task);
_before_processing.pop_front();
// check if more then one task available
if (_before_processing.size() > 1 && ident < _count)
_pool->borrow_thread(ident + 1, this, 1000);
}
void process_task(const processing_task& task)
{
mutex_keeper keeper(_mtx_queue);
_before_processing.push_back(task);
}
void print_results()
{
mutex_keeper keeper(_mtx_queue);
printf("total processed tasks are: %d\n\r", _before_processing.size());
printf("total not processed tasks are: %d\n\r", _after_processing.size());
}
private:
size_t _count;
mutex _mtx_queue;
std::list< processing_task > _before_processing;
std::list< processing_task > _after_processing;
terimber_thread_pool* _pool;
};
int main()
{
// max 10 thread
test_thread_client client(10);
// create tasks
processing_task task1(1);
processing_task task2(2);
processing_task task3(3);
processing_task task4(4);
// process task
client.process_task(task1);
client.process_task(task2);
client.process_task(task3);
client.process_task(task4);
// give threads a chance to process tasks
Sleep(1000);
// print results
client.print_results() ;
return 0;
}
|
|