相关疑难解决方法(0)

C++中类成员的类和std :: async

我试着写一个类成员,它并行多次调用另一个类成员.

我写了一个简单的问题示例,甚至无法编译.调用std :: async我做错了什么?我想问题就在于我如何传递函数.

#include <vector>
#include <future>
using namespace std;
class A
{
    int a,b;
public: 
    A(int i=1, int j=2){ a=i; b=j;} 

    std::pair<int,int> do_rand_stf(int x,int y)
    {
        std::pair<int,int> ret(x+a,y+b);
        return ret;
    }

    void run()
    {
        std::vector<std::future<std::pair<int,int>>> ran;
        for(int i=0;i<2;i++)
        {
            for(int j=0;j<2;j++)
            {
                auto hand=async(launch::async,do_rand_stf,i,j);
                ran.push_back(hand);    
            }
        }
        for(int i=0;i<ran.size();i++)
        {
            pair<int,int> ttt=ran[i].get();
            cout << ttt.first << ttt.second << endl;
        } 
    }
};

int main()
{
    A a;
    a.run();
}
Run Code Online (Sandbox Code Playgroud)

汇编:

g++ -std=c++11 -pthread main.cpp 
Run Code Online (Sandbox Code Playgroud)

c++ c++11

28
推荐指数
1
解决办法
2万
查看次数

使用静态链接启动std :: thread会导致分段错误

要学习c ++ 11(和boost)我正在使用boost asio和c ++ 11(用于线程和lambdas)编写一个简单的http服务器.

我想测试新的c ++ 11 lambdas和std :: thread,所以我尝试io_service.run()在带有lambda的std :: thread中启动这样的:

#include <iostream>
#include <thread>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
using std::cout;
using std::endl;
using boost::asio::ip::tcp;

class HttpServer
{
public:
    HttpServer(std::size_t thread_pool_size)
    : io_service_(),
    endpoint_(boost::asio::ip::tcp::v4(), 8000),
    acceptor_(io_service_, endpoint_)
    { }

    void Start() {
        acceptor_.listen();
        cout << "Adr before " << &io_service_ << endl;
        std::thread io_thread([this](){
            cout << "Adr inside " << &io_service_ << endl;
            io_service_.run();
        });
        io_thread.join();
    }

private:
    boost::asio::io_service io_service_;
    tcp::endpoint endpoint_;
    tcp::acceptor acceptor_;
}; …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

11
推荐指数
2
解决办法
2932
查看次数

标签 统计

c++ ×2

c++11 ×2