我在Mac OS Xcode 4.3.2上使用C++ 11 std :: async使用相同的线程,我的代码没有实现并行性.在下面的示例代码中,我想创建10个新线程.在每个线程中,我想计算输入变量的平方根并将结果设置为promise.在main函数中我想显示从线程计算的结果.我用策略启动:: async调用std :: async,所以我希望它创建一个新线程(10次).
#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 …Run Code Online (Sandbox Code Playgroud)