简体   繁体   中英

How to create a class that would have a 2 threads inside and array of public methods that are not in that threads? (C++, using Boost librarys)

So I want a C++ class to contain for example one public function: int summ(); that would return an int which would be created as sum of 2 variables (each of that variabes should be edited by one thread)

So generaly I need a sample like 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();
}

but sum should be not in main programm but in some class that our main programm would be capable to create and get that summ() when needed.

How to do such thing?

The example is a little strange, as the results would be random, depending on the exact coordination of the threads and sleep times. However, to get what you want, you have several options. You could create a new class with:

  • The code of your main function as a class method;
  • The c (sum) variable would be a class member;
  • The code of the method would return the sum.

Something like:

class TwoThreads
{
    int sum;

public:
    int doSomething()
    {
        // Same code as in main, using "sum" as the accumulator variable
        return sum;
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM