mutex和lock_guard
對公共資源訪問不加鎖:
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int g_i = 0;
mutex g_mutex;
void c()
{
for (int i = 0; i < 20; ++i)
{
//g_mutex.lock();
cout << std::this_thread::get_id() << " " << g_i++ << endl;
//g_mutex.unlock();
}
}
int main()
{
thread t1(c);
thread t2(c);
if (t1.joinable())
t1.join();
if (t2.joinable())
t2.join();
system("pause");
return 0;
}
效果如下:
加鎖之後:
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int g_i = 0;
mutex g_mutex;
void c()
{
for (int i = 0; i < 20; ++i)
{
g_mutex.lock();
cout << std::this_thread::get_id() << " " << g_i++ << endl;
g_mutex.unlock();
}
}
int main()
{
thread t1(c);
thread t2(c);
if (t1.joinable())
t1.join();
if (t2.joinable())
t2.join();
system("pause");
return 0;
}
使用:lock_guard
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int g_i = 0;
mutex g_mutex;
void c()
{
for (int i = 0; i < 20; ++i)
{
lock_guard<mutex> lock(g_mutex);
cout << std::this_thread::get_id() << " " << g_i++ << endl;
}
}
int main()
{
thread t1(c);
thread t2(c);
if (t1.joinable())
t1.join();
if (t2.joinable())
t2.join();
system("pause");
return 0;
}