Sobes.tech
Middle

When a single physical core executes two threads, will this happen synchronously or in parallel?

sobes.tech AI

Answer from AI

This occurs synchronously in terms of simultaneous execution at the same micro-moment in time. A single physical resource (core) cannot execute two tasks absolutely in parallel.

The Android OS uses preemptive multitasking. The core switches between threads, allocating small time slices to each. This creates the illusion of parallelism (concurrency).

// Example: preemptive multitasking
fun main() {
    val thread1 = Thread {
        for (i in 1..5) {
            println("Thread 1: $i")
            Thread.sleep(10) // Simulating work
        }
    }

    val thread2 = Thread {
        for (i in 1..5) {
            println("Thread 2: $i")
            Thread.sleep(10) // Simulating work
        }
    }

    thread1.start()
    thread2.start()
}

In the example above, we see that the output lines from both threads alternate, demonstrating context switching between them.

Concepts:

  • Parallelism: The simultaneous execution of multiple tasks at the same moment in time on multiple physical CPUs or cores.
  • Synchronous / Concurrency: The execution of multiple tasks over a certain period of time, where the processor rapidly switches between tasks, creating the illusion of their simultaneous execution.

Thus, on a single core, multiple threads are executed synchronously (concurrently) through context switching.

When a single physical core executes two threads… - sobes.tech