Sobes.tech
Junior — Middle

How to implement the execution of commands simultaneously on a single processor core?

sobes.tech AI

Answer from AI

In Go, single-threaded execution of multiple commands on one CPU core is achieved using goroutines — lightweight threads that the Go scheduler distributes across available system threads. Even if you have only one core, goroutines will run concurrently, switching between each other, creating the illusion of simultaneous execution.

To do this, simply launch functions as goroutines using the go keyword:

package main

import (
    "fmt"
    "time"
)

func task(name string) {
    for i := 0; i < 5; i++ {
        fmt.Println(name, "is running", i)
        time.Sleep(100 * time.Millisecond)
    }
}

func main() {
    go task("Goroutine 1")
    go task("Goroutine 2")

    // Wait for goroutines to finish
    time.Sleep(1 * time.Second)
}

Even on a single core, goroutines will switch by the scheduler, creating the illusion of concurrent execution. To control the number of OS threads used, you can use runtime.GOMAXPROCS(1).

import "runtime"

func main() {
    runtime.GOMAXPROCS(1) // limit execution to one core
    // launch goroutines
}
How to implement the execution of commands… - sobes.tech