万行代码计划 day02,50行代码 一起学习,共同成长 目前进度,100/10000
/*20210727 多线程同步,原子操作,临界区用法, 学习视频:(66-70讲)多线程编程,(临界区 mutex) */
#include #include #include #include #include #include #include #include #include #include
class Counter { public: Counter():m_count{0},m_totalResource{0}{}; void addCountAndResouce(int r){ std::lock_guardstd::mutex lock(m_mutex); addCount(); addResource?; } int count() const{ std::lock_guardstd::mutex lock(m_mutex); return m_count; } int aveResource(){ std::lock_guardstd::mutex lock(m_mutex); if (m_count==0){ return 1; } return m_totalResource/m_count; }
private:
int m_count;
int m_totalResource;
mutable std::mutex m_mutex;
void addResource(int r){m_totalResource++;}
void addCount(){m_count++;}
};
int work(int a) { // do some thing return a + a; }
template void realWork(Counter &c, double &totalValue, Iter b, Iter e) { for (; b != e; ++b) { try { totalValue += work(*b); // print some vaule // debugPrintInfo?; c.addCountAndResouce(1); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); } catch(…) { } } }
bool printStep(Counter &c, int maxCount) { auto count = c.count(); if (count == maxCount) { std::cout << " ok finished \n"; return true; } return false; }
int main() { std::vector vec; double totalValue = 0; for(int i = 0; i < 100; ++i) { vec.push_back(rand() % 100); } Counter counter; auto beginc = clock(); realWork(counter, totalValue, vec.begin(), vec.end()); auto endc = clock(); // do work std::cout << "total times: " << counter.count() << " " << totalValue<< " using time "<<endc-beginc<<std::endl;
//分出两个线程执行
totalValue = 0;
Counter counter2;
beginc = clock();
std::thread printCount([&counter2] {
while (!printStep(counter2, 100))
;
});
auto iter = vec.begin() + (vec.size() / 3);
auto iter2 = vec.begin() + (vec.size() / 3 * 2);
std::thread b([&counter2, &totalValue, iter, iter2] {
realWork(counter2, totalValue, iter, iter2);
});
auto end = vec.end();
double totalC = 0;
std::thread c([&counter2, &totalC, iter2, end] {
realWork(counter2, totalC, iter2, end);
});
double totalM = 0;
realWork(counter2, totalM, vec.begin(), iter);
b.join();
c.join();
auto realTotalCount = counter2.count();
totalValue += totalC + totalM;
endc = clock();
std::cout << "total times use multithread: " << realTotalCount << " " << totalValue << " using time "<<endc-beginc<<std::endl;
printCount.join();
}
|