关于C++中的 _InterlockedIncrement 函数

//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
原文链接: https://www.cnblogs.com/0patrick/p/14197680.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/206612

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午10:37
下一篇 2023年2月12日 下午10:39

相关推荐