Mutex/Locks Implementation

Most mutual exclusion and synchronization mechanisms use hardware atomic operations. However, it is possible to implement mutual exclusion entirely in software.

Some language-level mutex implementations rely on machine-level support such as Test-and-set.

Atomic operations -- Test-and-set

In computer science, the test-and-set instruction is an instruction used to write 1 (set) to a memory location and return its old value as a single atomic (i.e., non-interruptible) operation. If multiple processes may access the same memory location, and if a process is currently performing a test-and-set, no other process may begin another test-and-set until the first process's test-and-set is finished. A CPU may use a test-and-set instruction offered by another electronic component, such as dual-port RAM; a CPU itself may also offer a test-and-set instruction.

int test_and_set(int x) // let x be strictly either 0 or 1.
{
if (x) { return 1; } else { x=1; return 0; }
}

All this needs to be implemented atomically, in hardware.

A lock can be built using an atomic test-and-set instruction as follows:

function Lock(boolean *lock) { 
    while (test_and_set(lock) == 1); 
}

The calling process obtains the lock if the old value was 0 otherwise while-loop spins waiting to acquire the lock. This is called a spinlock.

//implement thread lock(l) simply as
while test_and_set(l) { do nothing; } // spinlock version of thread_lock()
 volatile int lock = 0;
 
 void Critical() {
     while (TestAndSet(&lock) == 1);
     critical section // only one process can be in this section at a time
     lock = 0 // release lock when finished with the critical section
 }

The assembly instruction test and set can be made to be atomic across multiple processors. An equivalent option would be an atomic compare and swap assembly instruction.

These low-level hardware solutions are then built up into high-level functions, either built into the languages, or in libraries. In general, do not implement your own locking functions, but rather use functions from a tested library. Getting things right can be tricky, and your own solution is also likely to be non-portable.

more ref:

https://stackoverflow.com/questions/1485924/how-are-mutexes-implemented

https://stackoverflow.com/questions/1726702/how-are-mutex-and-lock-structures-implemented

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,186评论 0 10
  • 为什么那么多人看不惯有钱人,却努力想成为有钱人,是不是很矛盾? 人是欲望的生物。有社会属性的人,比起所有...
    熊玲心理咨询阅读 1,841评论 1 0
  • 1. 我的女儿两岁四个月,她的性格属于传统意义上的典型的女孩。乖巧、文静、温柔、体贴、善解人意、爱分享,不打架。我...
    林资言阅读 4,304评论 0 1
  • 产业突破核心科技的藩篱,要从基础做起。不夸张地说,现代产业的根本在基础研究,基础研究的根本在基础教育,基础教育的...
    義華安徽樅陽阅读 3,638评论 0 2
  • 【每天懂点香学】沉香不像黄金和钻石那样有闪亮的外表,但是它也有它独特的一面,暗沉的颜色,纹理不规则地排列着,透漏着...
    Daniel均衡阅读 2,642评论 1 2

友情链接更多精彩内容