[英]Can two processes run the same method at the exact same time on a single-core CPU machine?
I have studied that an operating system time-slices the processes.我研究过操作系统对进程进行时间切片。
I know that we should design a multi-thread application assuming that it may be run on multicore CPU.我知道我们应该设计一个多线程应用程序,假设它可以在多核 CPU 上运行。 Just for the sake of knowledge, I want to know if there is a possibility of two processes running the same method at the exact same time on a single-core CPU machine.
只是为了知识,我想知道两个进程是否有可能在单核 CPU机器上同时运行相同的方法。
...run the same method at the exact same time...
...在完全相同的时间运行相同的方法...
The answer depends on what you think that phrase means.答案取决于您认为该短语的含义。
In order to understand the execution of a program, you have to talk about events, and the order in which events happen.为了理解程序的执行,您必须谈论事件以及事件发生的顺序。 Events are instantaneous, and on a single core machine no two events can ever happen at the same time.
事件是瞬时的,在单核机器上不可能同时发生两个事件。
But, "running a method" is not an event.但是,“运行方法”不是一个事件。 Running a method is the interval between two events;
运行一个方法是两个事件之间的间隔; The first event is the method call, and the second event is the return.
第一个事件是方法调用,第二个事件是返回。 Even on a single-core machine, two method calls can be overlapped:
即使在单核机器上,两个方法调用也可以重叠:
method call A method call B
---------------- ----------------
- entered
does some work
- entered v
does some work | during this span of time
does some work | the two method calls are
does some work | _overlapped._
... |
- returns ^
does some work
- returns
...the same method...
……同样的方法……
Watch out there!当心! "Thread-safety" is practically never a question of which methods are called by the application's threads.
“线程安全”实际上从来不是应用程序线程调用哪些方法的问题。 It's a question of which data the methods operate on.
这是方法对哪些数据进行操作的问题。
Two overlapping calls to the same method can operate on different data, and have no impact on thread-safety whatsoever.对同一方法的两次重叠调用可以对不同的数据进行操作,并且对线程安全没有任何影响。
Two overlapping calls to different methods can operate on the same data, and need to use mutexes or other special means to ensure that they do not interfere with each other and corrupt the data as a result.对不同方法的两次重叠调用可以对同一数据进行操作,并且需要使用互斥锁或其他特殊手段来确保它们不会相互干扰并因此破坏数据。
The answer is straightforward we cannot do multithreading in a single-core CPU as we need at least two cores to run a thread simultaneously.答案很简单,我们不能在单核 CPU 中进行多线程,因为我们需要至少两个内核来同时运行一个线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.