gpt4 book ai didi

c++ - 不使用 boost 线程的等效 c++0x 程序

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:00:34 25 4
gpt4 key购买 nike

我有以下使用 boost 线程的简单程序,在 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;
}

最佳答案

没什么变化可言...

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

关于c++ - 不使用 boost 线程的等效 c++0x 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2915972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com