Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <iostream>
- #include <boost/thread.hpp>
- #include <boost/bind.hpp>
- #include <queue>
- #include <string>
- #include <vector>
- class WorkerManager
- {
- boost::thread_group _tg;
- std::queue<std::string> _queue;
- boost::mutex _mutex;
- boost::condition_variable _cvar;
- bool _done;
- public:
- WorkerManager()
- {
- _done = false;
- for(int i = 0; i < boost::thread::hardware_concurrency(); ++i)
- {
- _tg.create_thread(boost::bind(&WorkerManager::Run, this));
- }
- }
- void Join()
- {
- _tg.join_all();
- }
- void Run()
- {
- while(true)
- {
- std::string item;
- {
- boost::mutex::scoped_lock lock(_mutex);
- while(_queue.empty() && !_done)
- _cvar.wait(lock);
- if (_queue.empty() && _done)
- return;
- item = _queue.front();
- _queue.pop();
- }
- Execute(item);
- }
- }
- void Execute(std::string s)
- {
- std::cout << "Run: " << s << std::endl;
- }
- void Add(std::string item)
- {
- boost::mutex::scoped_lock lock(_mutex);
- _queue.push(item);
- _cvar.notify_one();
- }
- void Complete()
- {
- boost::mutex::scoped_lock lock(_mutex);
- _done = true;
- _cvar.notify_one();
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- WorkerManager manager;
- manager.Add("job");
- manager.Add("job");
- manager.Add("job");
- manager.Add("job");
- manager.Add("job");
- manager.Add("job");
- manager.Add("job");
- manager.Add("job");
- manager.Complete();
- manager.Join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement