这里的代码是为了引入一个问题:线程安全
#include<iostream> #include<thread>//线程头文件 #include<future>//简单说std::future提供了一种访问异步操作结果的机制 #include<cmath>//数学操作头文件 #include<vector> #include<chrono>//获取本机器参考线程数的头文件 #include<cstdlib>//C语言中的stdlib.h在C++被重命名为cstdlib #include<ctime>////C语言中的time.h在C++被重命名为ctime using 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 <class Iter> 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<int> 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,++的过程中,无法操作,也就会漏掉本次操作,造成所谓“线程安全问题”
原文地址:https://www.cnblogs.com/zhangthree/p/10989158.html
时间: 2024-10-06 01:52:23