万行代码计划 day02 C++多线程同步

万行代码计划
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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值