samj
asked on
using boost thread for a simple code
Hi
the code below compiles and runs, but does not do what I want.
how can I get the code below to print out:
"I am child 1sub thread called."
thanks
************************** ********** ********** ********** **********
#include <boost/thread/thread.hpp>
#include <string>
#include <iostream>
using namespace std;
class Child
{
string c;
public:
Child(string x):c(x){ }
void operator()(){
cout << c << " sub thread called." << endl;
}
};
class Parent
{
string p;
public:
Parent(string x):p(x){}
void operator()(){
cout << p << "thread called." << endl;
Child c1("I am child 1");
boost::thread c1t(c1);
}
};
int main(){
Parent p1("I am parent 1: ");
boost::thread p1t(p1);
}
the code below compiles and runs, but does not do what I want.
how can I get the code below to print out:
"I am child 1sub thread called."
thanks
**************************
#include <boost/thread/thread.hpp>
#include <string>
#include <iostream>
using namespace std;
class Child
{
string c;
public:
Child(string x):c(x){ }
void operator()(){
cout << c << " sub thread called." << endl;
}
};
class Parent
{
string p;
public:
Parent(string x):p(x){}
void operator()(){
cout << p << "thread called." << endl;
Child c1("I am child 1");
boost::thread c1t(c1);
}
};
int main(){
Parent p1("I am parent 1: ");
boost::thread p1t(p1);
}
ASKER
that did not quite fix it. however the fix was to add join() to each of the Parent and Child objects like this
#include <boost/thread/thread.hpp>
#include <string>
#include <iostream>
using namespace std;
class Child
{
string c;
public:
Child(string x):c(x){ }
void operator()(){
cout << c << " sub thread called." << endl;
}
};
class Parent
{
string p;
public:
Parent(string x):p(x){}
void operator()(){
cout << p << "thread called." << endl;
Child c1("I am child 1");
boost::thread c1t(c1);
c1t.join();
}
};
int main(){
Parent p1("I am parent 1: ");
boost::thread p1t(p1);
p1t.join();
}
#include <boost/thread/thread.hpp>
#include <string>
#include <iostream>
using namespace std;
class Child
{
string c;
public:
Child(string x):c(x){ }
void operator()(){
cout << c << " sub thread called." << endl;
}
};
class Parent
{
string p;
public:
Parent(string x):p(x){}
void operator()(){
cout << p << "thread called." << endl;
Child c1("I am child 1");
boost::thread c1t(c1);
c1t.join();
}
};
int main(){
Parent p1("I am parent 1: ");
boost::thread p1t(p1);
p1t.join();
}
ASKER
I will ask to split the points and award you 75 for your attempt.
yes, it's just a example.
anyway, it's a pleasure to help:)
anyway, it's a pleasure to help:)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
first , cout is not thread safe, the output result is hard to predict.
second, after you create thread, us thread.join to wait thread finish.
like this:
Child c1("I am child 1");
boost::thread c1t(c1);
c1t.join();//wait thread finish