在C++11中,引入了有关线程的一系列库.且都在std命名空间内.下面演示一个使用线程的例子.非常的简单.引入了thread和mutex头文件.
#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;
}
//打印结果.
932 0
10340 1
932 2
10340 3
932 4
我们使用mutex互斥锁,来保证线程的安全性.但是这样是很麻烦的.我们需要手动的对锁进行操作.如果出现多个分支的情况,则需要多次书写unlock操作.
所以引入了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;
}
//它被用作临时变量来使用,用g_mutex锁进行初始化,初始化的时候就是锁的lock操作的时候,那么什么时候unlock呢?就是在超出它的作用域之后析构时unlock.
//初始化时lock.
explicit lock_guard(_Mutex& _Mtx)
: _MyMutex(_Mtx)
{ // construct and lock
_MyMutex.lock();
}
lock_guard(_Mutex& _Mtx, adopt_lock_t)
: _MyMutex(_Mtx)
{ // construct but don't lock
}
//析构时unlock.
~lock_guard() _NOEXCEPT
{ // unlock
_MyMutex.unlock();
}