I don't understand multithreaded programming

Can someone please explain to me how a multi-threaded application can be faster when a single-core processor can only do one thing at a time. If I have 10 threads, then only one of these threads really "works" at any given time on a single processor core, and all additional threads just add the overhead of context switching. Therefore, if there are 10 instructions for processing in each thread, then at the end I still process 100 instructions sequentially, as well as the overhead of the context. Did I miss something?

+3
source share
5 answers

Yes, you miss the fact that a process can block I / O expectations. Thus, if you use ONE THREAD only in your application, if it blocks the wait for I / O to complete, it will be very slow.

On the other hand, if you have multiple threads, your application may have a couple of them waiting for I / O to complete, but the rest of them are “running”, while the OS gives it access to SINGLE PROCESSOR.

Keep in mind that I / O operations are less by an order of magnitude slower than CPU operations .

. , , , . , APACHE, . , , -, , -. , ASYNC-IO. , Apache, ASYNC-IO, , , - .

+9

4- . . 4 , ?

, , .

, , 5 .

, , , .

- - (, -, ..). . .

+16

, . . "" . - , , , . . , . , . , . - , .

+1

In one core, of course, this is not faster. But this can make the system more responsive without being dead to the world, performing a long-term task.

0
source

Actually, it depends on what the threads do. If there is a relatively large delay, another thread can do its job, and other threads are waiting for themselves.

0
source

Source: https://habr.com/ru/post/1774587/


All Articles