这里的代码是为了引入一个问题:线程安全
#include#include //线程头文件#include //简单说std::future提供了一种访问异步操作结果的机制#include //数学操作头文件#include #include //获取本机器参考线程数的头文件#include //C语言中的stdlib.h在C++被重命名为cstdlib#include C语言中的time.h在C++被重命名为ctimeusing namespace std;class Counter{public: Counter():m_count {0}{} void addCount() { m_count++; } int count() const { return m_count; }private: int m_count;};int work(int a){ return a + a;}template void realWork(Counter &c, double &totalValue, Iter itBegin,Iter itEnd){ for (; itBegin != itEnd; itBegin++) { totalValue += work(*itBegin); c.addCount(); }}//并发量int main(){ unsigned int n = thread::hardware_concurrency(); cout << "本机器参考线程数:" << n << endl; vector vec; double totalValue = 0; for (int i = 0; i < 10000000; i++) { vec.push_back(rand() % 100); } Counter counter; for (auto v :vec) { totalValue += work(v); counter.addCount(); } cout << "total times" << counter.count() << endl; Counter counter2; auto iter = vec.begin() + vec.size() / 3; auto iter2 = vec.begin() + vec.size() / 3 * 2; thread b([&counter2, &totalValue, iter, iter2] { realWork(counter2, totalValue, iter, iter2); }); auto vEnd = vec.end(); thread c([&counter2, &totalValue, iter2, vEnd] { realWork(counter2, totalValue, iter2, vEnd); }); realWork(counter2, totalValue, vec.begin(), iter); b.join(); c.join(); cout << "线程调用的counter2:" << counter2.count() << endl;}
运行结果如下:
本机器参考线程数:4
total times10000000线程调用的counter2:9964868为什么会少呢?是因为线程操作相同的变量++的时候i,++的过程中,无法操作,也就会漏掉本次操作,造成所谓“线程安全问题”