Async or multithreading? Both make code faster, but they fix completely different problems.
RickTheEngineer
Visit on TikTok@rick.theengineer58K followers
13,100 views #programming #async #multithreading
Async or multithreading? Both make code faster, but they fix completely different problems. Picture a backend handling 1,000 requests, each waiting 100 ms on a database. Written as plain blocking code, one thread handles them one at a time: 100 seconds. And for almost all of it, the CPU does nothing but wait on the network. There are two ways out. → Multithreading gives each request its own thread. While one is blocked, the operating system switches the CPU to another, and on a multi-core CPU threads run truly at the same time, one per core. That’s parallelism. → But threads aren’t free: • every thread needs memory for its own stack • switching between them (a context switch) costs CPU time • threads share memory, so two can change the same data at once, which is a race condition • locks fix races, but used carelessly, threads wait on each other forever, which is a deadlock → Async keeps one thread and stops it from wasting time. It starts the query, moves on immediately, and an event loop resumes each task when its data arrives. Every await hands control back to the loop, so one thread can juggle thousands of open connections with very little memory. That’s concurrency: many tasks in progress, but only one running at any instant. → Its weakness: a heavy calculation never hits an await, so it holds the thread and every other task freezes. Real languages mix both ideas: ✓ Go runs thousands of lightweight goroutines on a small pool of real threads ✓ Java’s virtual threads work in a similar way ✓ Standard Python has the GIL, so only one thread runs Python code at a time. Threads still help with waiting, but heavy math needs multiple processes, and newer versions offer an optional build without the lock The mental model: ✓ Waiting on networks and databases? Async shines. ✓ Crunching numbers? You need parallelism. Which one does your current project lean on more? #programming #async #multithreading #concurrency #softwareengineering
Comments
Comments from the original post on TikTok
No comments yet
