zoukankan      html  css  js  c++  java
  • c++11多线程学习笔记之二 mutex使用

    // 1111111.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include <iostream>
    #include <thread>
    #include <mutex>         
    
    int gcounter = 0;
    std::mutex gmtx;    
    std::mutex gmtxOutput;
    
    void Increases() {
    	for (int i = 0; i<10000; ++i) {
    		if (gmtx.try_lock()) {   // only increase if currently not locked:
    			++gcounter;
    			gmtx.unlock();
    		}
    		else{
    			gmtxOutput.lock();
    			std::cout << "try lock failed" << std::endl;
    			gmtxOutput.unlock();
    		}
    	}
    }
    
    int _tmain(int argc, _TCHAR* argv[]) {
    	std::thread threads[10];
    	for (int i = 0; i<10; ++i)
    		threads[i] = std::thread(Increases);
    
    	for (auto& th : threads) 
    		th.join();
    	std::cout << "counter is " << gcounter << std::endl;
    
    	return 0;
    }
    

    输出:

    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    try lock failed
    counter is 99983
    请按任意键继续. . .

     这个例子说明了 try_lock() 与 lock()的区别

    try_lock()会对能否上锁进行测试 并返回布尔值

    而lock()则直接进行锁定 不能锁定则阻塞直到锁定

  • 相关阅读:
    冒泡排序
    获取某年某月有多少天 & 常用日期转换
    left join,right join ,inner join
    Left join加上where条件的困惑
    ORACLE查询练习
    Ch25 文件和注册表操作(2)-- 读写文件
    Ch25 文件和注册表操作(1)--文件系统
    C#入门经典札记_Ch05变量的更多内容
    C#入门经典札记_Ch04流程控制
    C#入门经典札记_Ch03变量和表达式
  • 原文地址:https://www.cnblogs.com/itdef/p/4559146.html
Copyright © 2011-2022 走看看