Sobes.tech
Middle+

Tell about locks and semaphores. What are locks needed for, and what is the difference between multithreaded and asynchronous modes?

sobes.tech AI

Answer from AI

Loki (mutex) and semaphores are synchronization mechanisms used to control access to shared resources in multithreaded or concurrent programs.

Mutex is a primitive that allows only one thread (or task) to own the resource at a specific time. If another thread tries to acquire the mutex, it is blocked until the mutex is released.

Semaphore is a more general mechanism that limits the number of threads that can work with a resource simultaneously. For example, a semaphore with a counter of 3 allows three threads to operate concurrently.


Difference between multithreaded and asynchronous modes:

  • Multithreaded mode involves multiple OS threads executing in parallel or concurrently, each capable of blocking and waiting.
  • Asynchronous mode (e.g., async/await) is cooperative multitasking, where tasks do not block the thread but yield control back to the scheduler while waiting for operations.

In multithreaded mode, mutexes and semaphores are used to prevent race conditions and ensure data integrity. In asynchronous mode, other primitives (e.g., asyncio.Lock in Python) are often used, which do not block the thread but suspend the coroutine.

Example of mutex in Python:

import threading

lock = threading.Lock()

with lock:
    # critical section
    pass

Example of an asynchronous lock:

import asyncio

lock = asyncio.Lock()

async def critical_section():
    async with lock:
        # asynchronous critical section
        pass