std::mutex
#include <iostream>
#include <vector>
#include <mutex>
#include <thread>
using namespace std;
volatile int counter = 0;
void ft1()
{
for (int i = 0; i < 100000; ++i)
{
++counter;
}
}
int main()
{
std::vector<std::thread> ts;
for(int i = 0; i < 5; ++i)
{
ts.emplace_back(std::thread(ft1));
}
for (auto& t : ts)
{
t.join();
}
cout << counter << endl;
system("pause");
return 0;
}
輸出結(jié)果: counter 小于 5 * 100000
#include <iostream>
#include <vector>
#include <mutex>
#include <thread>
using namespace std;
volatile int counter = 0;
std::mutex mtx;
void ft1()
{
for (int i = 0; i < 100000; ++i)
{
mtx.lock();
++counter;
mtx.unlock();
}
}
int main()
{
std::vector<std::thread> ts;
for(int i = 0; i < 5; ++i)
{
ts.emplace_back(std::thread(ft1));
}
for (auto& t : ts)
{
t.join();
}
cout << counter << endl;
system("pause");
return 0;
}
輸出結(jié)果: counter 等于 5 * 100000
測(cè)試發(fā)現(xiàn)在加鎖的情況下,輸出結(jié)果會(huì)慢很多,網(wǎng)上查閱c++11的mutex性能損耗比較大。
2. std::promise
#include <iostream>
#include <thread>
#include <future>
using namespace std;
volatile int counter = 0;
void ft1(std::future<int>& fut)
{
int x = fut.get();
cout << "x = " << x << "\n";
}
int main()
{
std::promise<int> prom;
std::future<int> fut = prom.get_future();
std::thread t(ft1, std::ref(fut));
prom.set_value(10); // 注釋該句ft1線程阻塞,知道fut.get()獲取到set_vaule()的值
t.join();
system("pause");
return 0;
}
3. std::atomic<T>
#include <iostream>
#include <vector>
#include <mutex>
#include <thread>
#include <atomic>
using namespace std;
std::atomic<int> counter(0);
void ft1()
{
for (int i = 0; i < 100000; ++i)
{
++counter;
}
}
int main()
{
std::vector<std::thread> ts;
for(int i = 0; i < 5; ++i)
{
ts.emplace_back(std::thread(ft1));
}
for (auto& t : ts)
{
t.join();
}
cout << counter << endl;
system("pause");
return 0;
}
測(cè)試性能由于std::mutex