// C++11_Mutex.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
volatile int counter(0); // non-atomic counter
std::mutex mtx; // locks access to counter
std::mutex numLock;
std::mutex gNumLock;
volatile int gNum(0);
/**
* Copyright(C) JnVision Corporation 2018 All Rights Reserved.
* @version V1.0
* @date 2018-05-17
* @author wangsl
* @brief mutex常见函数lock,unlock,try_lock,以及lock_guard和get_id的用法实例
多个线程同时进行时,mutex mtx的状态未知,所以有的成功有的失败,
加入lock_guard后互斥进行加锁解锁操作,此时counter结果为100000
*/
void attempt_10k_increases(int k) {
std::lock_guard<std::mutex> lockNum(numLock);
std::cout <<std::this_thread::get_id() << ":" << k << std::endl;
for (int i = 0; i < 10000; ++i) {
if (mtx.try_lock()) { // only increase if currently not locked:
++counter;
mtx.unlock();
}
}
//std::lock_guard<std::mutex> lockGNum(gNumLock);
gNum++;
std::cout << gNum << std::endl;
}
int main(int argc, const char* argv[]) {
std::thread threads[10];
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(std::bind(attempt_10k_increases,i));
//join表示线程结束后与主线程汇合,与之相对的为detach
for (auto& th : threads) th.join();
std::cout << counter << " successful increases of the counter.\n";
system("pause");
return 0;
}
C++11学习之Thread——Mutex
猜你喜欢
转载自blog.csdn.net/lasuerte/article/details/80354251
今日推荐
周排行