C++11学习之Thread——Mutex

// 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值