tags:

views:

165

answers:

1

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;
}
+1  A: 

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();
}
Motti
While running the program , I get an error message "terminate called without an active exception Aborted ". What does this signify ?
Eternal Learner
I think we still need to use thr1.join();
Eternal Learner
@Eternal, oops my bad, I misremembered you **do** have to call `join`:§ 30.3.1.3 1133_If joinable() then terminate(), otherwise no effects. [ Note: Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable. —end note ]_
Motti