65,189
社区成员




#include <iostream>
#include <boost/thread.hpp>
using namespace std;
#include "windows.h"
class TestA
{
public:
TestA(int x)
{
cout << "new TestA()" << endl;
x_ = x;
}
int GetX()
{
return x_;
}
void SetX(int x)
{
x_ = x;
}
private:
int x_;
};
class TestVC
{
public:
TestVC()
{
running_flag = true;
}
void stop()
{
running_flag = false;
{
boost::recursive_mutex::scoped_lock lock(mtx);
cond.notify_all();
}
}
void waitSignalThread(TestA& texta)
{
boost::recursive_mutex::scoped_lock lock(mtx);
while(running_flag)
{
// cout << "start wait signal" << endl;
cond.wait(mtx);
cout << "texta x value is : " << texta.GetX() << endl;
// cout << "finish wait signal" << endl;
}
}
void emitSignalThread(TestA& texta)
{
int i = 100;
while (running_flag)
{
{
boost::recursive_mutex::scoped_lock lock(mtx);
cout << "start emit singal" << endl;
texta.SetX(i--);
// cout << "texta x value is : " << texta.GetX() << endl;
cond.notify_one();
Sleep(100);
cout << "finish emit signal" << endl;
}
}
}
private:
bool running_flag;
boost::recursive_mutex mtx;
boost::condition_variable_any cond;
};
int main()
{
boost::thread_group grp;
TestVC test;
TestA testa(0);
grp.create_thread(boost::bind(&TestVC::waitSignalThread, &test, boost::ref(testa)));
grp.create_thread(boost::bind(&TestVC::emitSignalThread, &test, boost::ref(testa)));
// test.stop();
grp.join_all();
return 0;
}
void emitSignalThread(TestA& texta)
{
int i = 100;
while (running_flag)
{
{
boost::recursive_mutex::scoped_lock lock(mtx);
cout << "start emit singal" << endl;
texta.SetX(i--);
// cout << "texta x value is : " << texta.GetX() << endl;
cond.notify_one();
// Sleep(100);
cout << "finish emit signal" << endl;
}
Sleep(100);
}
}