gpt4 book ai didi

multithreading - "mutex"和 "atomic operation"之间有什么区别吗?

转载 作者:行者123 更新时间:2023-12-04 04:30:21 24 4
gpt4 key购买 nike

我现在正在学习操作系统,我对这两个概念很困惑 - 互斥锁原子操作 .在我的理解中,它们是一样的,但是我的 OS 老师给了我们这样一个问题,

Suppose a multi-processor operating system kernel tracks the number of processes created by each user. This operating system kernel maintains a counter variable for each user that it increments every time it creates a new process for a user and decrements every time a process from that user terminates. Furthermore, this operating system runs on a processor that provides atomic fetch-and-increment and fetch-and-decrement instructions. Should the operating system update the counter using the atomic increment and decrement instructions, or should it update the counter in a critical section protected by a mutex?



这个问题说明互斥和原子操作是两件事。有人可以帮我吗?

最佳答案

atomic操作是一种不能分割为更小的部分。因此,它永远不会半途而废,因此您可以保证始终以一致的状态观察它。例如,现代硬件实现了原子比较和交换操作。

A 互斥锁 ( mutual exclusion 的缩写)排除其他进程或线程执行相同的代码段( critical section )。基本上,它确保最多有一个线程正在执行给定的代码段。互斥锁也称为 lock .

在幕后,锁必须以某种方式使用硬件实现,并且实现必须利用底层硬件的原子性保证。

大多数非平凡的操作都不能成为原子操作,因此您必须使用锁来阻止其他线程在临界区执行时进行操作,否则您必须仔细设计一个 lock-free algorithm这确保所有关键的状态更改操作都可以使用原子操作安全地实现。

这是一个非常深刻的主题,并且有大量关于所有这些主题的文献。我提供的 Wikipedia 链接是一个很好的起点,但是由于您现在正在上操作系统类(class),因此最好请您的教授提供学习和理解这些内容的良好资源。

关于multithreading - "mutex"和 "atomic operation"之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32833786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com