原子操作跨进程的工作方式与跨线程的工作方式相同吗?
显然,原子操作可确保不同的线程不会破坏值。但是,当使用共享内存时,跨进程仍然如此吗?即使进程碰巧被操作系统安排在不同的内核上运行?或者跨不同的不同CPU?
编辑:此外,如果它不安全,那么即使在像 Linux 这样的操作系统上(从调度程序的角度来看进程和线程是相同的)也是不安全的吗?
Obviously, atomic operations make sure that different threads don't clobber a value. But is this still true across processes, when using shared memory? Even if the processes happen to be scheduled by the OS to run on different cores? Or across different distinct CPUs?
Edit: Also, if it's not safe, is it not safe even on an operating system like Linux, where processes and threads are the same from the scheduler's point of view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
tl;dr: 阅读原子操作文档中的细则。有些在设计上是原子的,但可能会绊倒某些变量类型。不过,一般来说,原子操作将在不同进程之间维护其契约,就像在线程之间一样。
原子操作实际上只能确保两个实体同时调用时不会出现不一致的状态。例如,由两个不同的线程或进程对同一整数调用的原子增量将始终表现如下:
其中 A 和 B 表示进行调用的第一个和第二个线程或进程。
由于竞争条件、对地址空间的不完整写入等,非原子操作可能会导致不一致或通常疯狂的结果。例如,您可以轻松地看到:
请注意实体 B 超越 A 并首先完成表达式时的竞争条件。
现在想象一下,如果 x 是一个 64 位双精度数,并且不能确保具有原子赋值。在这种情况下,您可以很容易地看到类似这样的内容:
这些非原子分配是您必须诊断的最可怕的并发错误之一。
tl;dr: Read the fine print in the documentation of the atomic operations. Some will be atomic by design but may trip over certain variable types. In general, though, an atomic operation will maintain its contract between different processes just as it does between threads.
An atomic operation really only ensures that you won't have an inconsistent state if called by two entities simultaneously. For example, an atomic increment that is called by two different threads or processes on the same integer will always behave like so:
where A and B indicate the first and second thread or process that makes the call.
A non-atomic operation can result in inconsistent or generally crazy results due to race conditions, incomplete writes to the address space, etc. For example, you can easily see this:
Note the race condition as entity B races past A and completes the expression first.
Now imagine if x were a 64-bit double that is not ensured to have atomic assignments. In that case you could easily see something like this:
These non-atomic assignments are some of the most hideous concurrent bugs you'll ever have to diagnose.