C++ 11的 mutex 比windows的功能相对丰富,和 boost mutex 基本类似,C++11 mutex主要分为以下4种
| std::mutex | 基本mutex |
| std::recursive_mutex | 递归mutex,可以多重加锁解锁 |
| std::timed_mutex | 延时mutex, 到了一定时间自动解锁 |
| std::recursive_timed_mutex | 递归延时mutex |
在使用C++11的mutex需要包含如下头文件
#include
using namespace std;
下面用卖火车票的例子讲解各种mutex的使用,代码如下:
#include
#include
#include
using namespace std;
using namespace std::this_thread;
using namespace std::chrono;
int g_Tickets = 100;
void ThreadFunc(string &str)
{
while (g_Tickets > 0)
{
if (g_Tickets > 0)
{
sleep_for(chrono::milliseconds(100));
printf("%s正在卖%d张票\n&
