InterlockedIncrement64与托管C ++ [英] InterlockedIncrement64 with managed C++

查看:388
本文介绍了InterlockedIncrement64与托管C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将在Visual Studio 2012下编写的代码移植到Visual Studio 2015中编译。代码在Windows 2012中构建成功。

I'm porting code written under Visual Studio 2012 to compile with Visual Studio 2015. The code builds OK with Windows 2012.

我遇到了一些问题调用 InterlockedIncrement64 。它为x64目标构建确定,但是在目标是Win32并且调用代码被管理(即使用 / clr )的情况下失败,产生:

I have an issue with some code that calls InterlockedIncrement64. It builds OK for an x64 target, but fails where the target is Win32 and the calling code is managed (i.e. compiled with /clr), yielding:


错误C3861:'InterlockedIncrement64':未找到标识符

error C3861: 'InterlockedIncrement64': identifier not found

在winnt.h中,当目标是Win32并且定义 _MANAGED 时,似乎 InterlockedIncrement64

Looking in winnt.h, it seems that InterlockedIncrement64 is undefined when the target is Win32 and _MANAGED is defined.

我可以重新安排代码,使得 InterlockedIncrement64 不会被托管代码调用,但我仍然好奇

I can rearrange the code such that InterlockedIncrement64 isn't called for managed code, but I'm still curious to know why this change in behavior has come with Visual Studio 2015.

推荐答案

顾名思义, InterlockedIncrement64 是 LONGLONG 的原子递增操作,它需要64位对齐

As the name implies, InterlockedIncrement64 is an atomic increment operation for a LONGLONG, and it needs memory to be 64 bit aligned.

由于您无法在托管代码中设置内存对齐,并且它可能用于托管类成员,则此限制对我有意义: ...否则,此函数在多处理器x86系统和任何非x86系统上的行为都是不可预测的。。想想这个:

Given that you can't set memory alignment in managed code and it may be used for managed class members then this limitation makes sense (to me): "...otherwise, this function will behave unpredictably on multiprocessor x86 systems and any non-x86 systems.". Think about this:

::InterlockedIncrement64(&_memberVariable);

如果 _memberVariable 托管世界,那么它不会是64位对齐(虽然它可能偶然发生),并且此代码将总是失败为Win32 。定义 _MANAGED

解决方法:检查 #ifdef _MANAGED ,然后调用 Interlocked :: Increment ,否则丢弃原子性包括增量后的内存屏障。

Workaround: check #ifdef _MANAGED and call Interlocked::Increment instead, or drop atomicity (!) but include a memory barrier after increment.

这篇关于InterlockedIncrement64与托管C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆