从哪里获得简单的升压线程管理的例子吗? [英] Where to get simple Boost Thread Management example?
本文介绍了从哪里获得简单的升压线程管理的例子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个简单的cpp文件。只有一个一个的主要功能和3 int类型的香格里拉公共变量。这样的:
So I have a simple cpp file. Only one with one main function and 3 int a-la public variables. like:
int a;
int b;
int c;
void main()
{
startThredA();
startThredB();
while(1)
{
c = a + b;
printf(c);
}
}
我whant创建2 threds A和B的其中之一应该产生A和随机值对B另一个随机值。如何做这样的事?
I whant to create 2 threds A and B one of which should generate random value for A and another random value for b. How to do such thing?
推荐答案
下面是一个小而简单的例子。它尝试,似乎很好地工作。
Here is a small and simple example. It's tried and seems to work fine.
#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();
}
这篇关于从哪里获得简单的升压线程管理的例子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文