首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建一个包含两个线程的类,以及不在这些线程中的公共方法数组?(C++,使用Boost库)

如何创建一个包含两个线程的类,以及不在这些线程中的公共方法数组?(C++,使用Boost库)
EN

Stack Overflow用户
提问于 2010-11-08 07:41:28
回答 1查看 177关注 0票数 0

例如,我希望C++类包含一个公共函数:int summ();,它将返回一个int,它将被创建为2个变量之和(每个变量都应该由一个线程编辑)

所以一般来说,我需要一个像this这样的样本。

代码语言:javascript
复制
#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()

这样的事情怎么做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-11-08 07:57:37

这个例子有点奇怪,因为结果是随机的,这取决于线程和睡眠时间的精确协调。然而,为了得到你想要的,你有几个选择。您可以使用以下命令创建一个新类:

  • 将主函数的代码作为类方法;
  • c (sum)变量将是类成员;
  • 该方法的代码将返回sum。

类似于:

代码语言:javascript
复制
class TwoThreads
{
    int sum;

public:
    int doSomething()
    {
        // Same code as in main, using "sum" as the accumulator variable
        return sum;
    }
};
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4120313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档