Is Multithreading parallel or context switching?

Hey everyone i have little confusion about multithreading. I know that a single core:

In single core though, because it can only run single thread at a time, it has to stop processing the first thread to give chance to second thread, before giving chance to thread T2, it saves the state of T1 and switches over to T2 this in fact is Context switching.

So based this defination lets say there is 2 different cpu bound task (t1 and t2) and each task takes 10 second if run these by using multithreading must take 20 second total .

But when i make research more detaily i have met with 2 different situation
First image
how_multithreading_works_with_four_program_threads-f_mobile
Second image
1_0KqxBjbiEriVNjbnZWkRfA

First image is thats what i know (concurrent) but second image its basically parallel.
Which one is right ? Would be good if i can have good explanation.

You are mixing several concepts here. Maybe reading about how tokio queues tasks might give you some insights: Making the Tokio scheduler 10x faster | Tokio - An asynchronous Rust runtime

If your PC only has a single core this is basically right.

The first image is presumably intended to show what's happening inside a single CPU core where it switches between executing different threads. The second image's multithreading part shows what's happening in two threads, where each thread executes independently. They're not talking about the same thing so they're both right and not in conflict.

1 Like

Lets say i have setup a websocket server to aws ec2 (cheapest instance 512mb ram single cpu single core).
And spawned a thread for every inbound client connection .
In total i have 200 connected client so i must be switching extremely fast between clients then ?

Yes, and this is what your computer does all the time, tens or hundreds of times per second, because any modern desktop environment with a few applications open has hundreds of threads spawned for various purposes. However, most of these threads spend most of their time sleeping, waiting for a signal to wake up when they get some work to do. Almost always this is related to waiting for I/O, because almost any I/O is extremely slow compared to how fast the CPU is. Infinitely more so for network I/O, where the CPU could easily execute millions of instructions in the time it takes to make a simple roundtrip network request.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.