Haijun Si

concurrency

Jun 27, 2024 | thursday 5:14 pm

when, what, why is concurrency?

when: Concurrency originates from early operating system engineering efforts to optimize CPU resource utilization.

why: Concurrency enables programs to operate more efficiently. In today’s world, platforms such as Instagram and TikTok rely on concurrency to maintain responsiveness as millions of users like you, me, or others scroll, post, and interact with various features of the platform.

what: Concurrency in computing is the execution of a program happens in an unordered manner to give the illusion that multiple things are running at the same time.

the most trivial example is having two functions running concurrently:

  1. one that prints numbers
  2. one that prints letters

Example (Python)


    def print_numbers():
        for i in range(1, 4):
            print(f"Number: {i}")
            time.sleep(1)  # Simulate some work or delay

    def print_letters():
        for char in 'abc':
            print(f"Letter: {char}")
            time.sleep(1)  

    thread1 = threading.Thread(target=print_numbers)
    thread2 = threading.Thread(target=print_letters)

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

Sample Output:


    Number: 1
    Letter: a
    Number: 2
    Letter: b
    Number: 3
    Letter: c

this gives the illusion that these functions are running at the same time, when actually they are being threaded, which is a common technique to achieve concurrency in many programming languages.