关键部分内的 InterlockedExchange(或类似的原子操作)?

发布于 2025-01-05 23:09:00 字数 261 浏览 1 评论 0原文

我看到了一些重复的代码(准确地说是方法),它们进入关键部分,然后使用 InterlockedExchange...这有意义吗,因为我认为这个操作实际上是原子的,不需要这样的同步?

{ 
  EnterCricSectionLock lock (somelock);
  InterlockedExchange(&somelong, static_cast<long>(newlongVal));
}

基本上就是这样...

I have seen some repeated code (methods to be precise) where they are entering the critical section and then using InterlockedExchange...Does this make sense since I thought that this operation was infact atomic and would not require such synchronization?

{ 
  EnterCricSectionLock lock (somelock);
  InterlockedExchange(&somelong, static_cast<long>(newlongVal));
}

That is basically what there is...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

翻身的咸鱼 2025-01-12 23:09:00

正常的交换通常不是原子的。然而,如果所有其他用途都受到同一互斥体的保护,那么在拥有互斥体时执行此操作是可以的。如果所有其他用途都是原子的,那么使用原子交换也是可以的。我能想到在拥有互斥体的同时进行原子交换的唯一逻辑原因是,并非该值的所有使用都受到互斥体保护。

A normal exchange is generally not atomic. It is however ok to do it while owning a mutex, if all other uses is protected by the same mutex. It is also ok to use an atomic exchange, if all other uses are atomic. The only logical reason I can think of to do an atomic exchange while owning the mutex, is that not all uses of this value is mutex protected.

咆哮 2025-01-12 23:09:00

单个原子操作不需要 CS,但它可以充当栅栏,在锁保持全局可见时进行任何更改(IIRC,显式栅栏适用于 SSE2+,但互锁操作根本不需要 SSE),然而,它需要位于任何全球商店之后。

这可能有意义的是,CS 用于锁定对其他内容的访问,因此全局交换不是锁定的一部分。

A single atomic operation won't need a CS, but it can act as a fence to make anything altered while the lock is held globally visible (IIRC, explicit fences are for SSE2+, but interlocked ops don't need SSE at all), however then it would need to be after any global stores.

Where this might make sense is that the CS is used to lock access to something else, and thus global being exchanged on is not part of the lock.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文