Eternal Learner
Eternal Learner

Reputation: 3870

Equvalent c++0x program withought using boost threads

I have the below simple program using boost threads, what would be the changes needed to do the same in c++0X

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

boost::mutex mutex;

struct count
{
    count(int i): id(i){}

    void operator()()
    {
        boost::mutex::scoped_lock lk(mutex);
        for(int i = 0 ; i < 10000 ; i++)
        {
            std::cout<<"Thread "<<id<<"has been called "<<i<<" Times"<<std::endl;
        }
    }
    private:
        int id;
};

int main()
{
    boost::thread thr1(count(1));
    boost::thread thr2(count(2));
    boost::thread thr3(count(3));

    thr1.join();
    thr2.join();
    thr3.join();

    return 0;
}

Upvotes: 2

Views: 719

Answers (1)

Motti
Motti

Reputation: 114765

No changes to speak of...

#include <iostream>
#include <thread>

std::mutex mutex;

struct count {
    count(int i): id(i){}
    void operator()()
    {
        std::lock_guard<std::mutex> lk(mutex); // this seems rather silly...
        for(int i = 0 ; i < 10000 ; ++i)
            std::cout << "Thread " << id << "has been called " << i 
                << " Times" << std::endl;
    }
private:
    int id;
};

int main()
{
    std::thread thr1(count(1));
    std::thread thr2(count(2));
    std::thread thr3(count(3));

    thr1.join();
    thr2.join();
    thr3.join();
}

Upvotes: 2

Related Questions