Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute two threads asynchronously using boost?

I have the book "beyond the C++ standard library" and there are no examples of multithreading using boost. Would somebody be kind enough to show me a simple example where two threads are executed using boost- lets say asynchronously?

like image 529
user997112 Avatar asked Sep 15 '12 12:09

user997112


People also ask

Does boost asio use multiple threads?

Two I/O service objects are used next to two alarm clocks of type boost::asio::steady_timer in Example 32.4. The program is based on two threads, with each thread bound to another I/O service object.

Can multiple threads read the same memory?

Not only are different cores allowed to read from the same block of memory, they're allowed to write at the same time too.


1 Answers

This is my minimal Boost threading example.

#include <boost/thread.hpp>
#include <iostream>

using namespace std;

void ThreadFunction()
{
    int counter = 0;

    for(;;)
    {
        cout << "thread iteration " << ++counter << " Press Enter to stop" << endl;

        try
        {
            // Sleep and check for interrupt.
            // To check for interrupt without sleep,
            // use boost::this_thread::interruption_point()
            // which also throws boost::thread_interrupted
            boost::this_thread::sleep(boost::posix_time::milliseconds(500));
        }
        catch(boost::thread_interrupted&)
        {
            cout << "Thread is stopped" << endl;
            return;
        }
    }
}

int main()
{
    // Start thread
    boost::thread t(&ThreadFunction);

    // Wait for Enter 
    char ch;
    cin.get(ch);

    // Ask thread to stop
    t.interrupt();

    // Join - wait when thread actually exits
    t.join();
    cout << "main: thread ended" << endl;

    return 0;
}
like image 79
Alex F Avatar answered Oct 14 '22 10:10

Alex F