ThreadPool examples

#include "aconnect/types.hpp"
#include "aconnect/thread_pool.hpp"
#include "aconnect/util.hpp"

boost::detail::atomic_count COUNTER (0l);

void threadProc (int n)
{
	using namespace aconnect;
	util::sleep (rand() * 200/  RAND_MAX );
	std::cout << string ("threadProc: " + boost::lexical_cast<string> (n) + "\n" );

	++COUNTER;
}

int main (int argc, char* args[]) 
{
	using namespace aconnect;

	ThreadPool<int> pool(threadProc, 10);
	
	const int Count = 30;
	for (int n=0; n < Count; ++n) {
		aconnect::util::sleep (20);
		
		pool.process(n);
	}
	
	aconnect::util::sleep (1000);
	pool.wait();

	if (COUNTER == Count)
		std::cout << "All work done" << std::endl;
	else
		std::cout << "Error occured, there are unprocessed items (((." << std::endl;
}

Usage of ThreadPool is very clear - just create ThreadPool object and call process method for each item to process. Work items have to satisfy all constraints for items in std::vector (should have public copy-constructor and so on).

Class interface

template <typename P,  typename Container = std::queue<typename P> >
	class ThreadPool
	{
	public:
		typedef boost::function1<void, const typename P&> worker_thread_proc;

		ThreadPool (worker_thread_proc worker_proc = 0, int maxWorkersCount = 50, IStoppable *controller = 0, Logger *logger = 0);
		
		void process (P item);
		void stop (bool joinAll);
		void wait ();
	}

Additional using samples see in ThreadPool UT.

Last edited Dec 7, 2009 at 3:07 PM by artiz, version 5

Comments

No comments yet.