Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <vector>
- #include <iostream>
- #include <future>
- #include <thread>
- #include <boost/timer.hpp>
- #include <boost/date_time/posix_time/posix_time.hpp>
- struct Trace {
- Trace(int id) : id_(id) {
- std::cout << " begin " << id_ << std::endl;
- }
- ~Trace() {
- std::cout << " end " << id_ << std::endl;
- }
- int id_;
- };
- int dummyExpensiveBlockingNetworkCall(int id) {
- Trace trace(id);
- int result = 0;
- boost::timer tm;
- while(tm.elapsed() < 10.0) {
- ++result; //busy sleep
- }
- return result;
- }
- void slow() {
- std::vector<std::future<int>> futures;
- for (int i = 0; i < 10; ++i)
- {
- auto fut = std::async(std::launch::async, [=]()
- {
- return dummyExpensiveBlockingNetworkCall(i);
- });
- futures.push_back(std::move(fut));
- }
- std::vector<int> resVec;
- std::for_each(futures.begin(), futures.end(), [&](std::future<int> & fut)
- {
- resVec.push_back(fut.get());
- });
- /*
- std::for_each(resVec.begin(), resVec.end(), [](int result) {
- std::cout << result << ", ";
- });
- */
- }
- void fast() {
- std::vector<std::thread> threads;
- for (int i = 0; i < 10; ++i)
- {
- auto th = std::thread([=]()
- {
- dummyExpensiveBlockingNetworkCall(i);
- });
- threads.push_back(std::move(th));
- }
- std::vector<int> resVec;
- std::for_each(threads.begin(), threads.end(), [&](std::thread& th)
- {
- th.join();
- });
- }
- int main()
- {
- slow(); //takes up to 100 seconds as some work does not start before others have finsihed. As in the work is not paralell even thoough we told it to use std::launch::async.
- /*
- output:
- begin 0
- begin 1
- begin 2
- end 0
- end end 1
- begin 3
- 2
- begin 4
- end 3
- end 4
- begin 5
- begin 7
- begin 6
- end 7
- begin 8
- end 6
- end 5
- begin 9
- end 8
- end 9
- */
- //fast(); //takes at most 10 seconds as all begin come before end. Work is truly parallell
- /*
- output:
- begin 0
- begin 1
- begin 2
- begin 3
- begin 4
- begin 5
- begin 6 begin 8
- begin 7
- begin 9
- end 0 end 2
- end 5
- end 1
- end 3
- end 4
- end end 7
- end 6
- 8
- end 9
- */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement