开发者

Equvalent c++0x program withought using boost threads

开发者 https://www.devze.com 2023-01-01 17:34 出处:网络
I have the below simple program using boost threads, what would be the changes needed to do the same in c++0X

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::m开发者_JAVA技巧utex 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;
}


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号