c++boost

I'm trying to run C++ code that uses the Boost library


I would prefer not to download anything, but if I must, I can do so. I am just trying to run a simple multi-threaded program using the Boost library on many of the online compilers, but none of them even recognize

#include <boost/thread.hpp>

and

using namespace boost::this_thread;

The code itself is taken from this link: https://www.quantnet.com/threads/c-multithreading-in-boost.10028/

I have done my googling and tried out a lot of online compilers but none of them seem willing to recognize Boost or its associated libraries.

This is the code:

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

using namespace std;
using namespace boost;
using namespace boost::this_thread;

// Global function called by thread
void GlobalFunction()
{
   for (int i=0; i<10; ++i) {
       cout<< i << "Do something in parallel with main method." << endl;
       boost::this_thread::yield(); // 'yield' discussed in section 18.6
   }
}

int main()
{
    boost::thread t(&GlobalFunction);
    for (int i=0; i<10; i++) {
        cout << i <<"Do something in main method."<<endl;
    }
    return 0;
}

Solution

  • just use the C++11 threads. Ideone has threading disabled apparently but I had no problem running it on http://www.compileonline.com/ (just be sure to select C++11 and not C++)

    #include <iostream>
    #include <thread>
    // Global function called by thread
    void GlobalFunction()
    {
        for (int i = 0; i < 10; ++i)
        {
            std::cout << i << "Do something in parallel with main method." << std::endl;
            std::this_thread::yield(); // 'yield' discussed in section 18.6
        }
    }
    
    
    int main()
    {
        std::thread t(&GlobalFunction);
    
        for (int i = 0; i < 10; i++)
        {
            std::cout << i << "Do something in main method." << std::endl;
        }
    
    
        return 0;
    }