Boost logo

Boost Users :

Subject: [Boost-users] synchronize threads from a thread pool (using asio::io_service)
From: Daren Lee (dlee8854_at_[hidden])
Date: 2011-08-05 14:22:58


Hi -

I'm using asio::io_service as a dispatcher for a thread pool. I'm
wondering how I can synchronize the threads after I post the tasks to
the io_service.

I tried using a barrier but it doesn't always work correctly. The
barrier waits indefinitely; although I verified the post() function
gets called, the io_service doesn't seem to dispatch anything.

I've also thread using the boost::threadpool library but the overall
speed is slower.

I'd appreciate any insight on what I'm doing wrong with the barrier or
any other high performance thread pooling alternatives.

Thanks,
Daren

<code>
void handler ( int i, int nSize, double *pArray, double *pTemp,
boost::barrier *pBarrier )
{
    // compute on pArrray --> write result to pTemp[i]
    ....

    pBarrier->wait();
}

double doCalc ( int nSize, double *pArray, double *pTemp )
{
    unsigned  int nNumThreads = 8;
    int nSubSize = nSize / nNumThreads;

    boost::barrier barrier( nNumThreads + 1 );
    for( int i=0;i<nNumThreads;i++ )
    {
        if( i == nNumThreads-1 )
        {
             m_io_service.post( boost::bind( &handler, i,
nSize-(i*nSubSize), pArray+(i*nSubSize), pTemp, &barrier ));
        }
        else
        {
             m_io_service.post( boost::bind( &handler, i, nSubSize,
pArray+(i*nSubSize), pTemp, &barrier ));
        }
    }
    barrier.wait();

    // sum results
    double fSum = 0;
    for( int i=0;i<nNumThreads;i++ )
    {
        fSum += pTemp[i];
    }

    return fSum;
}

 I initialize the io_service with work elsewhere as:

    boost::asio::io_service::work m_work( m_io_service );

    boost::thread_group m_threads;
    for (std::size_t i = 0; i < m_nNumThreads; ++i)
        m_threads.create_thread(boost::bind(&boost::asio::io_service::run,
&m_io_service));

</code>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net