Golang goroutine process, thread, concurrency, parallelism

goroutine looks at a requirement


Requirement: It is required to count the numbers from 1 to 200000000000, which ones are prime numbers?

analysis of idea:

1) The traditional method is to use a loop to determine whether each number is a prime number (one task is assigned to one CPU, which is very uneconomical and very slow)

2) Use concurrent or parallel methods to assign the task of counting prime numbers to multiple goroutines to complete. In this case, goroutines will be used (speed is related to the number of cores)

Goroutine can perform concurrent and parallel processing, allowing a large task to be broken down into individual goroutines for completion.

 

Process and thread description


1) A process is an execution process of a program in the operating system and is the basic unit for resource allocation and scheduling in the system.

2) A thread is an execution instance of a process and the smallest unit of program execution. It is a basic unit that is smaller than a process and can run independently.

3) A process can create cores and destroy multiple threads, and multiple threads in the same process can execute concurrently.

4) A program has at least one process, a process, and at least one thread.

Double-clicking Thunder will start a process, and one Thunder can download multiple files. Each download task can be regarded as a thread, so that the CPU can maximize its performance.

Concurrency is not suitable for parallelism. In effect, it looks like 5 simultaneous downloads. In fact, the time slice is very short. From a micro perspective, only one file is downloading at a time point.

 

 

 

Concurrency and parallelism


1) Multi-threaded programs run on a single core , which means concurrency

2) Multi-threaded programs run on multiple cores , which is parallelism

Concurrency: Because it is on a CPU, for example, there are 10 threads, and each thread executes for 10 milliseconds (polling operation). From a human perspective, it seems that all 10 threads are running, but from a micro perspective, in At a certain point in time, there is actually only one thread executing, which is concurrency.

Parallelism: Because it is on multiple CPUs (for example, there are 10 CPUs), for example, there are 10 threads, each thread executes for 10 milliseconds (each executes on a different CPU), from a human perspective, these 10 threads are Running, but from a micro perspective, at a certain point in time, there are 10 threads executing at the same time. This is parallelism.

In traditional programming languages, even multiple tasks are assigned to one CPU, so multi-core cannot exert its power.

The go language is to transform concurrency into parallelism.

Guess you like

Origin blog.csdn.net/qq_34556414/article/details/132841317