ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [C++ Boost] boost::asio::strand ex1
    Search: 카테고리 없음 카테고리 없음 2016. 1. 28. 09:41

    //[C++ Boost] boost::asio::strand ex1

    //

    // 6126 jyj

    //


    //부적절한 예제 수정 필요.


    #include <boost/asio.hpp>

    #include <boost/thread.hpp>

    #include <boost/bind.hpp>

    #include <boost/date_time/posix_time/posix_time.hpp>



    namespace BoostAsioStrandTest01

    {

    boost::asio::io_service gIs;

    boost::asio::strand gStrand(gIs);

    int gCnt = 0;

    bool gbStrandOn = true;


    class Class1

    {

    public: //private:

    boost::asio::deadline_timer mDt;

    int mCc;

    public:

    Class1() : mDt(gIs, boost::posix_time::seconds(1)) {}


    void fun1()

    {

    if(gbStrandOn)

    {

    auto &gd = gStrand.wrap(boost::bind(&Class1::fun2, this)); gd();

    }

    else

    {

    this->fun2();

    }

    }

    void fun2()

    {

    if (gCnt >= 30) return;


    auto t1 = gCnt;

    std::cout << "Td" << mCc << " : " << gCnt << "\n";

    Sleep(1);

    gCnt = t1+1;




    mDt.expires_at(mDt.expires_at() + boost::posix_time::seconds(1));

    mDt.async_wait(boost::bind(&Class1::fun1, this)); //mDt.async_wait(gStrand.wrap(boost::bind(&Class1::fun2, this));

    }


    };



    int Main()

    {

    const int mc = 10;

    Class1 cs[mc];

    //race fun1;

    for(int i=0; i<mc; i++)

    {

    auto *p = &(cs[i]);

    p->mCc = i;

    }

    {

    for(int i=0; i<mc; i++)

    {

    auto *p = &(cs[i]);

    p->mDt.async_wait(boost::bind(&Class1::fun1, p));

    }


    boost::thread_group tg;


    for(int i=0; i<mc; i++)

    {

    tg.create_thread(boost::bind(&boost::asio::io_service::run, &gIs));

    }


    tg.join_all();


    std::cout << "end1: " << gCnt << std::endl; 

    }


    return 0;

    }


    }

    댓글