|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
万行代码计划
Day02,50行代码
#include <iostream>
#include <thread>
#include <future>
#include <cmath>
#include <vector>
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <atomic>
#include <mutex>
/*20210727
多线程同步,原子操作,临界区用法,
学习视频:(66-70讲)多线程编程,(临界区 mutex)
*/
class Counter
{
public:
Counter():m_count{0},m_totalResource{0}{};
void addCountAndResouce(int r){
std::lock_guard<std::mutex> lock(m_mutex);
addCount();
addResource(r);
}
int count() const{
std::lock_guard<std::mutex> lock(m_mutex);
return m_count;
}
int aveResource(){
std::lock_guard<std::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 <class Iter>
void realWork(Counter &c, double &totalValue, Iter b, Iter e) {
for (; b != e; ++b) {
try {
totalValue += work(*b);
// print some vaule
// debugPrintInfo(c);
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<int> 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();
}
|
|