例如,我希望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();
}但是sum不应该在主程序中,而应该在某个类中,这样我们主程序将能够在需要时创建和获取summ()。
这样的事情怎么做?
发布于 2010-11-08 07:57:37
这个例子有点奇怪,因为结果是随机的,这取决于线程和睡眠时间的精确协调。然而,为了得到你想要的,你有几个选择。您可以使用以下命令创建一个新类:
c (sum)变量将是类成员;类似于:
class TwoThreads
{
int sum;
public:
int doSomething()
{
// Same code as in main, using "sum" as the accumulator variable
return sum;
}
};https://stackoverflow.com/questions/4120313
复制相似问题