【问题标题】:Serializing part of work - boost::asio序列化部分工作 - boost::asio
【发布时间】:2011-04-21 11:33:01
【问题描述】:
    void wt(shared_ptr<io_service> io_servicee)
{
    io_servicee->run();
}

void calculateAndReturn(int myNumber, shared_ptr<vector<int> > vectorOfResults)
{
    /*
     * Here will be a lot of pararel computing (first part)...
     */

    int result = myNumber;

    /* This part (second part) below I want to be executed sequentially depending on the number of thread.
     * Thread which has myNumber == 1 should be first, second should be thread with
     * myNumber == 2, third with myNumber == 3 etc.
     *
     */
    mt.lock();
    vectorOfResults->push_back(result);
    mt.unlock();
}

int main()
{
    shared_ptr< io_service > io_servicee(new io_service);
    shared_ptr< io_service::work > work(new io_service::work( *io_servicee ));
    shared_ptr<vector<int> > vectorOfSums(new vector<int>);
    thread_group worker_threads;


    for( int x = 0; x < 4; ++x )
    {
            worker_threads.create_thread(bind( &wt, io_servicee ));
    }

    for( int x = 0; x < 4; ++x )
    {

        io_servicee->post(bind( &calculateAndReturn, x, vectorOfSums));
    }
    work.reset();
    worker_threads.join_all();

    for ( int i = 0; i < vectorOfSums->size(); i++)
    {
        cout << (*vectorOfSums)[i] << endl;

    }

}

我想序列化部分calculateAndReturn 函数。它应该是这样的:

First part of thread 1 ------->  \ 
                                  \
First part of thread 2 -------> -- Second part of thread 1 --> second part of thread2...
                                  /
     ....                        /
                                /
First part of thread n ------->/

我不想在 main 函数中使用 strand,而是在 calculateAndReturn 的第二部分之前使用。有什么优雅的解决方案吗?

最好的问候

【问题讨论】:

    标签: c++ multithreading boost boost-asio


    【解决方案1】:

    如果您在单个进程中执行此操作,我建议使用OpenMP。典型例子:

    #include <omp.h>
    #define N 1000
    #define CHUNKSIZE  100
    
    main ()  
    {
        int i, chunk;
        float a[N], b[N], c[N];
    
        /* Some initializations */
        for (i=0; i < N; i++)
          a[i] = b[i] = i * 1.0;
        chunk = CHUNKSIZE;
    
        #pragma omp parallel for shared(a,b,c,chunk) private(i) schedule(static,chunk)
        for (i=0; i < n; i++)
            c[i] = a[i] + b[i];
    }
    

    在 gnu 上:安装 libgomp,构建

    g++ -fopenmp -lgomp source.cpp
    

    【讨论】:

    • 我没听说过这个库,看起来很有用,你的代码更简单。但在这种情况下,我想使用 boost 和 asio 库,因为我想编写简单的 tcp 服务器。还是谢谢!
    猜你喜欢
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 2018-04-30
    • 2012-09-16
    • 2012-05-18
    • 1970-01-01
    相关资源
    最近更新 更多