Home > Back-end >  Boost the strand and the io_service scheduling problem?
Boost the strand and the io_service scheduling problem?

Time:09-24

First post code
 # include & lt; Iostream> 
#include
#include
#include
#include
#include

Boost: : an asio: : io_service m_service;
Boost: : an asio: : io_service: : strand m_strand (m_service);
STD: : mutex MTX.

Void print (int id) {
The lock ();//MTX.
//STD: : coutStatic int CNT=0;
STD: : cout<" Id: "& lt; + + CNT;
STD: : cout<" The count, "& lt; //MTX. Unlock ();
}

Void Run1 () {
Int ret.=m_service run_one ();
STD: : cout<" Run1 excute "& lt; }
Void Run2 () {
Int ret.=m_service run_one ();
STD: : cout<" Run2 excute "& lt; }


Void print1 () {
M_strand. Dispatch (m_strand. Wrap (STD: : bind (print, 1)));
}

Void print2 () {
M_strand. Post (m_strand. Wrap (STD: : bind (print, 2)));
}

Void print3 () {
M_strand. Post (m_strand. Wrap (STD: : bind (print, 3)));
}

Void print4 () {
M_strand. Post (m_strand. Wrap (STD: : bind (print, 4)));
}

Void test () {
STD: : thread t1 (print1);
STD: : thread t2 (print2);
STD: : thread t3 (print3);
STD: : thread t4 (print4);

//STD: : thread ios1 (Run1);
//STD: : thread ios2 (Run2);

T1. The join ();
T2. The join ();
T3. The join ();
T4. The join ();

//ios1. The join ();
//ios2. The join ();

Int ret=m_service. The run ();
STD: : cout<" The Main thread excute "& lt; }

Int main (int arg c, const char * * argv) {
Try {
test();
}
The catch (STD: : exception& E) {
STD: : cout}
return 0;
}


Compile the code above, the main process in the test function call m_service. The run () function, you can perform four Handler, but the return value is 2, should not return to 4? Solve???

Another question, when I open two threads to invoke m_service. Run_one (), occasionally there will be a kind of situation, main process the run of the return value is 0, also called run_one () function of the two threads, will back 1, but print thread ID found that the two threads returns 1, a performs a Handler, another three Handler is carried out, the main process is an open, this is how to return a responsibility?????? (beginner, found the problem, a little confused, and great god teach again thanked first!)
  • Related