Some languages support multiple threads, thread-safe data structures and cross-thread communication. Some languages also support asynchronous invocation of functions that may be waiting for an external asynchronous operation (e.g. IO, external process).
Concurrency
Python Concurrency
TypeScript Concurrency
Async/Await
Ability to seamlessly invoke and wait for an asynchronous operation, without blocking the executing thread. This typically requires runtime support to yield to an execution loop, where execution can continue until the asynchronous operation has completed.
Async Functions: The Equivalent of Goroutines
Python provides the async def
syntax for defining asynchronous functions. These functions must be awaited using the await
keyword to execute properly.
import asyncio async def async_task(): print("Task started") await asyncio.sleep(2) # Simulate work print("Task finished") async def main(): asyncio.create_task(async_task()) # Runs concurrently print("Main function continues...") await asyncio.sleep(3) # Wait for the task to complete asyncio.run(main())
Await Equivalent - Async Queues for Communication
Python's asyncio.Queue
provides a way for coroutines to communicate safely.
import asyncio async def worker(queue): await queue.put("Task completed") async def main(): queue = asyncio.Queue() asyncio.create_task(worker(queue)) msg = await queue.get() # Like await, wait to receive a message print(msg) # Output: Task completed asyncio.run(main())
Buffered vs Unbuffered Queues
Unbuffered queues (default) block until an item is received, while buffered queues allow adding multiple items without an immediate receiver (up to a limit).
import asyncio async def main(): queue = asyncio.Queue(maxsize=2) # Buffered queue with capacity 2 await queue.put(1) # Non-blocking put await queue.put(2) # Non-blocking put print(await queue.get()) # 1 print(await queue.get()) # 2 asyncio.run(main())
TypeScript supports async/await
for asynchronous operations.
async function fetchData(url: string): Promise<any> { const response = await fetch(url); return response.json(); } fetchData("https://api.example.com/data") .then((data) => console.log(data)) .catch((error) => console.error(error));
External Async Operations
Support in runtime libraries for native asynchronous operation (for example, file I/O). This alleviates the need to tie up a CPU thread while waiting on an external task to complete.
Python supports asynchronous file I/O using the aiofiles
library.
import aiofiles import asyncio async def read_file(file_path): async with aiofiles.open(file_path, mode='r') as file: contents = await file.read() print(contents) asyncio.run(read_file("example.txt"))
TypeScript relies on JavaScript's runtime for external asynchronous operations, such as file I/O or network requests.
const readFile = async (filePath: string) => { const response = await fetch(filePath); return response.text(); }; readFile("/path/to/file.txt") .then((content) => console.log(content)) .catch((error) => console.error("Error reading file:", error));
Multi-Threading
Supports the ability to create and manage preemptive operating system threads.
Python supports multi-threading using the threading
module.
import threading def worker(): print("Worker thread running") thread = threading.Thread(target=worker) thread.start() thread.join()
Not Supported
Atomic Operations and Mutexes
Supports the ability to coordinate access to shared resources (e.g. memory) across threads in the same process, and atomic operations (e.g. interlocked increment).
Python provides threading.Lock
for thread-safe operations.
import threading lock = threading.Lock() counter = 0 def increment(): global counter with lock: counter += 1 threads = [threading.Thread(target=increment) for _ in range(5)] for thread in threads: thread.start() for thread in threads: thread.join() print("Counter:", counter)
Not Supported
Semaphores and inter-thread communication
Ability to communicate between threads using semaphores and other inter-thread communication methods.
Semaphores and Inter-Thread Communication
Python provides threading.Semaphore
for inter-thread communication.
import threading import time semaphore = threading.Semaphore(2) def worker(): with semaphore: print("Worker started") time.sleep(1) print("Worker finished") threads = [threading.Thread(target=worker) for _ in range(5)] for thread in threads: thread.start() for thread in threads: thread.join()
Semaphores and Inter-Thread Communication
Not Supported
OS signal handlers
Integration with operating system signals (or Wait Handles).
OS Signal Handlers
Python supports OS signal handling using the signal
module.
import signal import time def handler(signum, frame): print("Signal received") signal.signal(signal.SIGINT, handler) print("Waiting for signal...") try: while True: time.sleep(1) except KeyboardInterrupt: print("Exiting")
OS Signal Handlers
Not Supported
Shared Memory
Ability to use shared memory for inter-process communication, either natively or through a commonly used library.
Python supports shared memory using the multiprocessing
module.
from multiprocessing import shared_memory shm = shared_memory.SharedMemory(create=True, size=1024) shm.buf[:11] = b"Hello World" print(bytes(shm.buf[:11]).decode()) shm.close() shm.unlink()
Not Supported