Luna Tech

Tutorials For Dummies.

Multithreads

2022-02-19


0. What is multi threads?

Sometimes a problem can be divided into multiple pieces to compute separately, this is called parallel programming, and we can use multiple threads to achieve it.

It makes use of CPU cores or available threads to achieve better performance.

Without multithreads we have to run them sequentially, thus taking more time.

prerequisite

Concurrency(并发) vs Parallelism(并行)

Concurrency is the task of running and managing the multiple computations at the same time. While parallelism is the task of running multiple computations simultaneously.

Concurrency is two lines of customers ordering from a single cashier (lines take turns ordering); Parallelism is two lines of customers ordering from two cashiers (each line gets its own cashier).

Concurrency 就是可以在做了一半 A 任务的时候去执行 B 任务。

Parallelism 就是可以同时执行 A、B 两个任务。

并发与并行的区别是什么?

How many core/threads do I have?

On Windows you can open Task Manager and check your CPU specs in the performance tab. 12 cores/threads means 12 concurrent operations.

Note: core and thread are interchangeable terms.

PPS: If your machine only has one core, you won’t benefit from parallelism.


1. Key Points

  1. Two ways of achieving parallel programming in .NET:
    1. use lower level thread class (more control, more responsibility, more code, more error-prone)
    2. use TPL’s abstraction (preferred way, manages threads for us)
  2. When to use Parallel programming?
    1. CPU bound operations
    2. Independent chunks of data
  3. When to use Async programming?
    1. I/O operations
    2. Waiting for other services to return result (e.g., calling APIs)
  4. Misusing Parallel in ASP.NET can cause bad performance for all users.
    • if a user invocation utilizes all the available cores on the server, the other users won’t be able to access the resource.
    • server side heavy computation based on invocation should be handled in other ways (architectural level)

Related Articles