Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <boost/thread.hpp>
- #include <vector>
- #include <queue>
- #include <algorithm>
- #include <string>
- boost::condition_variable condDoTask, condOutput;
- boost::mutex globalMutex;
- volatile bool isMissionComplete = false;
- void Encode(std::queue<std::pair<unsigned, std::string> >& in, std::map<unsigned, std::string>& out)
- {
- boost::mutex localMutex;
- while (true)
- {
- boost::mutex::scoped_lock lock(localMutex);
- condDoTask.wait(lock, [&in] { return !in.empty() || isMissionComplete; });
- if (isMissionComplete)
- break;
- globalMutex.lock();
- std::pair<unsigned, std::string> deal(std::move(in.front()));
- globalMutex.unlock();
- in.pop();
- ///////// DO YOUR TASK HERE //////////
- std::for_each(deal.second.begin(), deal.second.end(),
- [] (char& c) { c = std::isupper(c) ? std::tolower(c) : std::toupper(c); } );
- ///////// DO YOUR TASK HERE //////////
- globalMutex.lock();
- out.insert(std::move(deal));
- globalMutex.unlock();
- condOutput.notify_all();
- }
- condOutput.notify_all();
- }
- void Output(std::map<unsigned, std::string>& out, const volatile unsigned& total)
- {
- unsigned count = 0;
- boost::mutex localMutex;
- while (true)
- {
- boost::mutex::scoped_lock lock(localMutex);
- condOutput.wait(lock,
- [&out, count, &total] { return (!out.empty() && count == out.begin()->first) || ( isMissionComplete && count == total); });
- if (isMissionComplete && count == total)
- break;
- std::cout << out.begin()->second << std::endl;
- globalMutex.lock();
- out.erase(out.begin());
- globalMutex.unlock();
- ++count;
- }
- }
- int main()
- {
- enum { NumOfThread = 2 };
- boost::thread_group threads;
- std::queue<std::pair<unsigned, std::string> > in;
- std::map<unsigned, std::string> out;
- volatile unsigned count = 0;
- boost::thread outputThread(Output, std::ref(out), std::ref(count));
- for (int i=0; i!=NumOfThread; ++i)
- threads.create_thread(std::bind(Encode, std::ref(in), std::ref(out)));
- std::string str;
- while (std::cin >> str)
- {
- in.push(make_pair(count++, std::move(str)));
- condDoTask.notify_one();
- }
- isMissionComplete = true;
- condDoTask.notify_all();
- outputThread.join();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement