本文介绍了当两个线程ATTEMPT恰好同时锁定同一资源时,会发生什么情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当两个线程试图在完全相同的微秒(或可测量CPU片或指令的最短时间长度)内锁定同一对象时会发生什么?

What happens when two threads attempt to lock the same object at the exact same microsecond (or whatever is the smallest length of time a CPU slice or instruction can be measured at)?

两个线程是否有可能在完全相同的并发时间执行指令,还是当今的硬件无法实现?

Is it even possible for two threads to execute instructions at the exact same concurrent time, or is that an impossibility with today's hardware?

我正在从事一个涉及muitithreading的项目,可以这么说,任何线程都可能将另一个线程击败.很自然的问题是当他们都同时锁定时会发生什么?"必须解决IMO.

Im working on a project that deals with muitithreading, where any thread may beat the other to the finish line, so to speak. So naturally, the question of "What happens when they all lock at the same time?" has to be addressed IMO.

推荐答案

在几乎所有环境中,现代锁的设计都使得两个线程不可能同时锁定一个对象.现代处理器有可能使运行在两个不同内核上的两个线程几乎同时尝试获得锁,但是它们都实现了同步机制,该机制允许软件告知他们不允许这样做

Modern locks, in pretty much all environments, are designed such that it isn't possible for two threads to lock an object at the same time. It is possible for modern processors to have two threads running on two different cores attempt to take a lock at very nearly the same time, but they all implement synchronization mechanisms that allow software to tell them not to allow it.

例如,x86-64具有监视器 MWAIT 说明.它们实质上在微处理器级别上实现.NET的lock(){}System.Threading.Monitor.Wait()System.Threading.Monitor.Enter()/.Exit()的语义.

For example, x86-64 has MONITOR and MWAIT instructions. They essentially implement, at the microprocessor level, the semantics of .NET's lock(){}, System.Threading.Monitor.Wait() and System.Threading.Monitor.Enter()/.Exit().

这篇关于当两个线程ATTEMPT恰好同时锁定同一资源时,会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 06:29