KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am using C++11 on Mac OS Xcode 4.3.2 std::async uses same thread and my code does not achieve parallelism. In sample code below I want to create 10 new threads. In each thread I want to calculate square root of input variable and set the result in promise. in main function I want to display the results calculated from threads. I am calling std::async with policy launch::async, So I expect it to create a new thread(10 times). #include <mutex> #include <future> #include <thread> #include <vector> #include <cmath> #include <iostream> using namespace std; mutex iomutex; void foo(int i, promise<double> &&prms) { this_thread::sleep_for(chrono::seconds(2)); prms.set_value(sqrt(i)); { lock_guard<mutex> lg(iomutex); cout << endl << "thread index=> " << i << ", id=> "<< this_thread::get_id(); } } int main() { { lock_guard<mutex> lg(iomutex); cout << endl << "main thread id=>"<< this_thread::get_id(); } vector<future<double>> futureVec; vector<promise<double>> prmsVec; for (int i = 0; i < 10; ++i) { promise<double> prms; future<double> ftr = prms.get_future(); futureVec.push_back(move(ftr)); prmsVec.push_back(move(prms)); async(launch::async, foo, i, move(prmsVec[i])); } for (auto iter = futureVec.begin(); iter != futureVec.end(); ++iter) { cout << endl << iter->get(); } cout << endl << "done"; return 0; } However if I use std::thread, then I can achieve parallelism. #include <mutex> #include <future> #include <thread&g
Tags (comma-separated)
Save Edits
Cancel