首页 > 编程语言 > 详细

关于C++中的 _InterlockedIncrement 函数

时间:2020-12-27 18:08:51      阅读:41      评论:0      收藏:0      [点我收藏+]
//shared_ptr 源码中的对象引用次数 自增的实现,代码位于 memory文件中,  
//其中
_MT_INCR 的定义是:#define _MT_INCR(x) _INTRIN_RELAXED(_InterlockedIncrement)(reinterpret_cast<volatile long*>(&x))
void _Incref() noexcept { // increment use count
        _MT_INCR(_Uses);
    }

void _Incwref() noexcept { // increment weak reference count
        _MT_INCR(_Weaks);
    }                        

 

微软文档中的解释https://docs.microsoft.com/en-us/previous-versions/ms919120(v=msdn.10):

This function both decrements (decreases by one) the value of the specified 32-bit variable and checks the resulting value. InterlockedDecrement prevents more than one thread from using the InterlockedDecrement or InterlockedIncrement function to access the same variable simultaneously.

 

原子锁一般用来做为存保护时使用,特别是在多线程操作时。一次只允许一个线程对该变量进行操容作。
long a=0;
_interlockedincrement(&a);
a++;
_interlockeddecrement(&a);
就是对a加以保护,只允许当前线程对变量a进行操作,该线程运行完以后,其他线程才能对该变量进行操作,这个函数和interlockedincrement配合使用,一加一减

 参考链接:https://zhidao.baidu.com/question/557872110144089692.html

关于C++中的 _InterlockedIncrement 函数

原文:https://www.cnblogs.com/0patrick/p/14197680.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!