如何在线程完成后发布新作业?

时间:2011-08-31 07:30:27

标签: c++ multithreading boost

如何在之前的工作完成后发布新工作?有谁知道怎么做?

这是我尝试过的,但它不起作用:

boost::mutex global_stream_lock;

void WorkerThread( boost::shared_ptr< boost::asio::io_service > io_service )
{
    global_stream_lock.lock();
    std::cout << "[" << boost::this_thread::get_id()
              << "] Thread Start" << std::endl;
    global_stream_lock.unlock();

    io_service->run();

    global_stream_lock.lock();
    std::cout << "[" << boost::this_thread::get_id()
              << "] Thread Finish" << std::endl;
    global_stream_lock.unlock();
}

int main( int argc, char * argv[] ) {
    boost::shared_ptr< boost::asio::io_service > io_service( 
        new boost::asio::io_service
    );
    boost::shared_ptr< boost::asio::io_service::work > work(
        new boost::asio::io_service::work( *io_service )
    );

    boost::thread_group worker_threads;
    for( int x = 0; x < 2; ++x )
    {
        worker_threads.create_thread( boost::bind( &WorkerThread, 
                                                   io_service ) );
    }

    boost::this_thread::sleep( boost::posix_time::milliseconds( 1000 ) );

    io_service->post( boost::bind( &PrintNum, 1 ) );
    io_service->post( boost::bind( &PrintNum, 2 ) );
    io_service->post( boost::bind( &PrintNum, 3 ) );
    io_service->post( boost::bind( &PrintNum, 4 ) );
    io_service->post( boost::bind( &PrintNum, 5 ) );

    work.reset();

    worker_threads.join_all();

    work.reset(new boost::asio::io_service::work( *io_service ));
    io_service->reset();
    io_service->post( boost::bind( &PrintNum, 6 ) );
    work.reset();

    worker_threads.join_all();
    return 0;
}

0 个答案:

没有答案