Implementation of the Future Mode of GoLang Concurrent Programming

Implementation of the Future Mode of GoLang Concurrent Programming

I. Overview

​ In daily programming, you may encounter such a scenario. A task may have several things to do, and these things can be executed concurrently . In addition, we also need to get the results after the execution ends. , and use this for subsequent processing.

​ At this time, you can consider using the Future mode in Go programming

2. Code example

1. Build the structure FutureTask

​ Here we abstract what we are going to do into 任务, for each task we may need to 传递参数pass, and we also need to get this task 执行结果, for this, we create two channels, one for passing parameters and one for saving the result. (What other parameters are needed can be designed according to the specific business)

// FutureTask 在并发执行时用于传递参数和保存返回的结果
type FutureTask struct {
    
    
	// 用于传递参数
	args chan interface{
    
    }

	// 实际业务中可能还有很多其他的数据

	// 用于保存结果
	res chan interface{
    
    }
}

2. Create a goroutine to execute the future method

​ After creation FutureTask, you need to start goroutine to execute, for which you need to create an execution FutureTaskmethod

// execFutureTask 用于开启一个Future模式的线程
func execFutureTask(futureTask *FutureTask) {
    
    
	// 读取传入的参数
	fmt.Println("goroutine读取到的参数:", <-futureTask.args)

	// 这里可以执行具体的业务逻辑
	result := "执行完业务逻辑后得到的结果"

	// 将结果进行保存
	futureTask.res <- result
	defer close(futureTask.res)
	return
}

3. Test code

func main() {
    
    

	// 创建一个FutureTask并开启一个goroutine去执行
	futureTask := FutureTask{
    
    make(chan interface{
    
    }), make(chan interface{
    
    })}
	go execFutureTask(&futureTask)

	// 向FutureTask传入参数,如果不传的话会死锁
	futureTask.args <- "main线程传入的参数"

	// 这里可以并行的去执行一些其他业务逻辑
	time.Sleep(1 * time.Second)

	// 读取线程执行的
	fmt.Println("主线程读取future模式下goroutine的结果:", <-futureTask.res)
	
}

4. Execution results

goroutine读取到的参数: main线程传入的参数

主线程读取future模式下goroutine的结果: 执行完业务逻辑后得到的结果

3. Summary

​ This article introduces an implementation idea of ​​future, and the provided case code can be directly transformed and used. Because there is no dependency between goroutines, channels are used to achieve the effect of goroutines cooperating with each other.

​ Here is a little bit of knowledge: The Go language draws on "Communicating Squential Processes" (CSP), which is a paper by a big man in the computer field in the 20th century. The article abstracts the concurrent system into Channeland Process, the former is used to transmit messages, and the latter The two are independent of each other and have no affiliation, but messages are sent and received in a strict order.

Guess you like

Origin blog.csdn.net/weixin_44829930/article/details/123606804
Recommended