小编Vij*_*mar的帖子

std :: async使用相同的线程,我的代码没有实现并行性.

我在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)

c++ multithreading future promise c++11

8
推荐指数
1
解决办法
2614
查看次数

标签 统计

c++ ×1

c++11 ×1

future ×1

multithreading ×1

promise ×1