Home > other >  Can two processes run the same method at the exact same time on a single-core CPU machine?
Can two processes run the same method at the exact same time on a single-core CPU machine?

Time:09-27

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. 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.

CodePudding user response:

...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.

CodePudding user response:

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.

  • Related