0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

BoostAsio サンプル001:マルチスレッドとの仕事のやり取り

Posted at

最近になって、boost勉強中
やりこなせ、サンプル数
書き方やっぱりC言語風
ラップも仕事も迷走中
よーちぇけら

#仕事の依頼
出来るだけシンプルに、マルチスレッドワーカーに仕事を依頼したい
WorkerThreadってやつですね。
でも、依頼したい仕事のネタが同じデータなのでshard_ptrなんす

#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
class event_manager {
    boost::asio::io_service& io_service_;
    boost::shared_ptr<boost::asio::io_service::work> work_;
    boost::thread_group group_;
public:
    event_manager(boost::asio::io_service& io_service)
        : io_service_(io_service)
    {
        work_.reset(new boost::asio::io_service::work(io_service_));
        for (std::size_t i = 0; i < 3; ++i) {
            group_.create_thread(boost::bind(&boost::asio::io_service::run, &io_service_));
        }
    }
    void stop()
    {
        work_.reset();
        group_.join_all();
    }
    ~event_manager()
    {
        stop();
    }

};


class Work {
    boost::asio::io_service& io_service_;
    boost::asio::strand strand_;
    std::string name_;
public:
    explicit Work(boost::asio::io_service& io_service, const std::string& name)
        : io_service_(io_service), strand_(io_service), name_(name) {}
    void lets_do(std::shared_ptr<const std::string> msg)
    {
        io_service_.dispatch(strand_.wrap(boost::bind(&Work::doing, this, msg)));
    }
private:
    void doing(std::shared_ptr<const std::string> msg)
    {
    	std::cout <<  "start : " + name_ + " -------" << *msg << std::endl;
        boost::this_thread::sleep(boost::posix_time::seconds(2));
    	std::cout <<  "end   : " + name_ + " =======" << *msg << std::endl;
    }
};

int main()
{
	boost::asio::io_service io_service;
    event_manager manager(io_service);

    Work workA(io_service, "[Working A Job]");
    Work workB(io_service, "[Working B Job]");

	auto pt1 = std::make_shared<std::string>("pt1");

	std::cout << "Would you do work?" << std::endl;
    workA.lets_do(pt1);
    workA.lets_do(pt1);
    workB.lets_do(pt1);
    workB.lets_do(pt1);
    workA.lets_do(pt1);
	std::cout << "Sounds good ! pt1 working on thread." << std::endl;

	for(int i=0; i<10 ; i++){
		auto pt2 = std::make_shared<std::string>("pt:" + std::to_string(i));
	    workA.lets_do(pt2);
   	 	workB.lets_do(pt2);
	}
	std::cout << "Go it. All work doing." << std::endl;
	manager.stop();
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?