struct Counter {
int value;
void increment(){
++value;
}
};
int main(){
Counter counter;
std::vector<std::thread> threads;
for(int i = 0; i < 5; ++i){
threads.push_back(std::thread([&counter](){
for(int i = 0; i < 100; ++i){
counter.increment();
}
}));
}
for(auto& thread : threads){
thread.join();
}
std::cout << counter.value << std::endl;
return 0;
}
442 500 477 400 422 487
struct Counter {
std::mutex mutex;
int value;
Counter() : value(0) {}
void increment(){
mutex.lock();
++value;
mutex.unlock();
}
};
struct Counter {
int value;
Counter() : value(0) {}
void increment(){
++value;
}
void decrement(){
if(value == 0){
throw "Value cannot be less than 0";
}
--value;
}
};
struct ConcurrentCounter {
std::mutex mutex;
Counter counter;
void increment(){
mutex.lock();
counter.increment();
mutex.unlock();
}
void decrement(){
mutex.lock();
counter.decrement();
mutex.unlock();
}
};
void decrement(){
mutex.lock();
try {
counter.decrement();
} catch (std::string e){
mutex.unlock();
throw e;
}
mutex.unlock();
}
struct ConcurrentSafeCounter {
std::mutex mutex;
Counter counter;
void increment(){
std::lock_guard<std::mutex> guard(mutex);
counter.increment();
}
void decrement(){
std::lock_guard<std::mutex> guar(mutex);
mutex.unlock();
}
};
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有