Where can I get an example of simple Boost flow control?

So I have a simple cpp file. Only one with one main function and 3 a-la public variables. as:

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

I want to create 2 threds A and B, one of which should generate a random value for A and another random value for b. How to do it?

+1
source share
2 answers

Here is a small and simple example. He tried and seems to be working 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();
}
+3
source

There are a number of articles starting here that should give you some initial pointers. The writer is very responsible for attacking boost.thread in C ++ 0x.

:

++ 0x 1:

++ 0x 2:

++ 0x 3: -

++ 0x 4:

++ 0x 5: std:: unique_lock < >

++ 0x 6:

++ 0x 7:

++ 0x 8: , Promises

+2

All Articles