gpt4 book ai didi

c++ - 从哪里获得简单的 Boost 线程管理示例?

转载 作者:行者123 更新时间:2023-11-30 01:30:46 25 4
gpt4 key购买 nike

所以我有一个简单的 cpp 文件。只有一个具有一个主要功能和 3 个 int a-la 公共(public)变量。喜欢:

   int a;
int b;
int c;
void main()
{
startThredA();
startThredB();
while(1)
{
c = a + b;
printf(c);
}
}

我想创建 2 个线程 A 和 B,其中一个应该为 A 生成随机值,为 b 生成另一个随机值。怎么办?

最佳答案

这是一个小而简单的例子。它已经过尝试并且似乎工作正常。

#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();
}

关于c++ - 从哪里获得简单的 Boost 线程管理示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4102811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com