Итак, я хочу, чтобы класс C ++ содержал, например, одну публичную функцию: int summ();
, которая возвращала бы int
, который был бы создан как сумма 2 переменных (каждая из этих переменных должна редактироваться одним потоком)
В общем, мне нужен пример, подобный this :
#include <iostream>
#include <boost/thread.hpp>
namespace this_thread = boost::this_thread;
int a = 0;
int b = 0;
int c = 0;
class BaseThread
{
public:
BaseThread()
{ }
virtual ~BaseThread()
{ }
void operator()()
{
try
{
for (;;)
{
// Check if the thread should be interrupted
this_thread::interruption_point();
DoStuff();
}
}
catch (boost::thread_interrupted)
{
// Thread end
}
}
protected:
virtual void DoStuff() = 0;
};
class ThreadA : public BaseThread
{
protected:
virtual void DoStuff()
{
a += 1000;
// Sleep a little while (0.5 second)
this_thread::sleep(boost::posix_time::milliseconds(500));
}
};
class ThreadB : public BaseThread
{
protected:
virtual void DoStuff()
{
b++;
// Sleep a little while (0.5 second)
this_thread::sleep(boost::posix_time::milliseconds(100));
}
};
int main()
{
ThreadA thread_a_instance;
ThreadB thread_b_instance;
boost::thread threadA = boost::thread(thread_a_instance);
boost::thread threadB = boost::thread(thread_b_instance);
// Do this for 10 seconds (0.25 seconds * 40 = 10 seconds)
for (int i = 0; i < 40; i++)
{
c = a + b;
std::cout << c << std::endl;
// Sleep a little while (0.25 second)
this_thread::sleep(boost::posix_time::milliseconds(250));
}
threadB.interrupt();
threadB.join();
threadA.interrupt();
threadA.join();
}
, но сумма должна быть не в основной программе, а в каком-то классе, который наша основная программа могла бы создать иполучите это summ()
когда нужно.
Как это сделать?