How to do concurrency in go language

青灯夜游
Release: 2023-01-18 14:19:01
Original
1777 people have browsed it

Go language supports concurrency features through the compiler runtime (runtime); concurrency is completed through goroutine. Goroutine is a very lightweight implementation that can perform thousands of concurrent tasks in a single process. It is the core of the concurrency design of the Go language. You can create a goroutine using the go keyword, place the go declaration before a function that needs to be called, and call and run the function in the same address space, so that the function will be executed as an independent concurrent thread.

How to do concurrency in go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Concurrency means that multiple tasks can be executed at the same time. Concurrent programming has a broad meaning, including multi-thread programming, multi-process programming and distributed programs.

Go language supports concurrency features through the compiler runtime. Concurrency in Go language is accomplished through the goroutine feature. Goroutines are similar to threads, but multiple goroutines can be created to work concurrently as needed. Goroutine is scheduled by the runtime of the Go language, while threads are scheduled by the operating system.

The Go language also provides channels for communication between multiple goroutines. Goroutine and channel are important implementation foundations for the CSP (Communicating Sequential Process) concurrency model adhered to by the Go language.

Goroutine Introduction

Goroutine is a very lightweight implementation that can execute thousands of concurrent tasks in a single process , which is the core of Go language concurrency design.

After all, goroutine is actually a thread, but it is smaller than a thread. A dozen goroutines may be reflected in five or six threads at the bottom layer, and the Go language also implements memory sharing between goroutines.

Use the go keyword to create a goroutine, place the go declaration before a function that needs to be called, and call and run this function in the same address space, so that when the function is executed, it will act as an independent concurrent thread. This kind of thread is called goroutine in Go language.

The usage of goroutine is as follows:

//go 关键字放在方法调用前新建一个 goroutine 并执行方法体
go GetThingDone(param1, param2);
//新建一个匿名方法并执行
go func(param1, param2) {
}(val1, val2)
//直接新建一个 goroutine 并在 goroutine 中执行代码块
go {
    //do someting...
}
Copy after login

Because goroutine is parallel in a multi-core CPU environment, if the code block is executed in multiple goroutines, then we have achieved code parallelism.

If you need to know the execution of the program, how to get the parallel results? It needs to be used in conjunction with channel.

channel

channel is the communication method between goroutines provided by Go language at the language level. We can use channels to pass messages between two or more goroutines.

Channel is an intra-process communication method, so the process of passing objects through channels is consistent with the parameter passing behavior when calling functions. For example, pointers can also be passed. If cross-process communication is required, we recommend using a distributed system approach, such as using communication protocols such as Socket or HTTP. The Go language also has very complete support for the Internet.

Channel is type-related, that is to say, a channel can only pass one type of value, and this type needs to be specified when declaring the channel. If you know something about Unix pipes, it is not difficult to understand channel, which can be considered a type-safe pipe.

When defining a channel, you also need to define the type of value sent to the channel. Note that make must be used to create the channel. The code is as follows:

ci := make(chan int)
cs := make(chan string)
cf := make(chan interface{})
Copy after login

Back before the emergence of Windows and Linux In the ancient times, there was no concept of concurrency when developing programs, because the imperative programming language is based on serialization. The program will execute each instruction sequentially. The entire program has only one execution context, that is, a call stack and a heap. .

Concurrency means that the program has multiple execution contexts at runtime, corresponding to multiple call stacks. We know that when each process is running, it has its own call stack and heap, and a complete context. When the operating system schedules a process, it will save the context of the scheduled process. After the process obtains the time slice, Then restore the context of the process to the system.

From the perspective of the entire operating system, multiple processes can be concurrent, so what is the value of concurrency? Let’s look at the following scenarios first.

1) On the one hand, we need a responsive graphical user interface. On the other hand, the program also needs to perform a large number of operations or IO-intensive operations, and we need to make the interface response and operations execute at the same time.

2) When our Web server faces a large number of user requests, more "Web server work units" are needed to respond to users respectively.

3) Our transactions are in a distributed environment. The same work unit processes sharded data on different computers. The computer's CPU develops from a single core (core) to multiple cores, and we The programs are all serial, and the capabilities of the computer hardware are not fully utilized.

4) Our program is blocked due to IO operations, the entire program is in a stagnant state, and other IO-related tasks cannot be executed.

As you can see from the above examples, serial programs cannot meet our requirements in many scenarios. Below we have summarized several advantages of concurrent programs to make everyone realize that concurrency is imperative:

  • Concurrency can represent the problem model more objectively;

  • Concurrency can make full use of the advantages of the CPU core and improve the execution efficiency of the program;

  • Concurrency can make full use of the inherent asynchrony between the CPU and other hardware devices.

[Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of How to do concurrency in go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template