#include <iostream>
#include <string>
#include <thread>
#include <vector>
using std::thread;
using std::vector;
using std::cout;
using std::endl;
class Incrementer
{
private:
int counter;
public:
Incrementer() : counter{0} { };
void operator()()
{
for(int i = 0; i < 100000; i++)
{
this->counter++;
}
}
int getCounter() const
{
return this->counter;
}
};
int main()
{
// Create the threads which will each do some counting
vector<thread> threads;
Incrementer counter;
threads.push_back(thread(std::ref(counter)));
threads.push_back(thread(std::ref(counter)));
threads.push_back(thread(std::ref(counter)));
for(auto &t : threads)
{
t.join();
}
cout << counter.getCounter() << endl;
return 0;
}
g++ -std=c++11 -lpthread -o threading_example main.cpp
[lucas@lucas-desktop src]$ ./threading_example 218141 [lucas@lucas-desktop src]$ ./threading_example 208079 [lucas@lucas-desktop src]$ ./threading_example 100000 [lucas@lucas-desktop src]$ ./threading_example 202426 [lucas@lucas-desktop src]$ ./threading_example 172209
movl counter(%rip), %eax addl $1, %eax movl %eax, counter(%rip)
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include <mutex>
using std::thread;
using std::vector;
using std::cout;
using std::endl;
using std::mutex;
class Incrementer
{
private:
int counter;
mutex m;
public:
Incrementer() : counter{0} { };
void operator()()
{
for(int i = 0; i < 100000; i++)
{
this->m.lock();
this->counter++;
this->m.unlock();
}
}
int getCounter() const
{
return this->counter;
}
};
int main()
{
// Create the threads which will each do some counting
vector<thread> threads;
Incrementer counter;
threads.push_back(thread(std::ref(counter)));
threads.push_back(thread(std::ref(counter)));
threads.push_back(thread(std::ref(counter)));
for(auto &t : threads)
{
t.join();
}
cout << counter.getCounter() << endl;
return 0;
}
[lucas@lucas-desktop src]$ ./threading_example 300000 [lucas@lucas-desktop src]$ ./threading_example 300000
for(int i = 0; i < 100000; i++)
{
this->m.lock();
try
{
this->counter++;
this->m.unlock();
}
catch(...)
{
this->m.unlock();
throw;
}
}
void operator()()
{
for(int i = 0; i < 100000; i++)
{
lock_guard<mutex> lock(this->m);
// The lock has been created now, and immediatly locks the mutex
this->counter++;
// This is the end of the for-loop scope, and the lock will be
// destroyed, and in the destructor of the lock, it will
// unlock the mutex
}
}
void long_function()
{
// some long code
// Just a pair of curly braces
{
// Temp scope, create lock
lock_guard<mutex> lock(this->m);
// do some stuff
// Close the scope, so the guard will unlock the mutex
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有