golang is a natural language-level that supports concurrency, which is a great language. Sometimes when we are developing business, we encounter complex scenarios and need to be used for concurrency. Multiple requests are used to complete concurrency using coroutine groups. When we encounter nested loops, there is still a contextual relationship that needs to be transformed into concurrent requests. The previous time complexity is O(n^2) to O(n), so can we further reduce the time complexity to O(1)? Nested concurrency occurs. How to nest concurrency and how to write it. Today we will analyze step by step.
Serial execution
- Time complexity is O(n^2)
- Don't use concurrency
- The result execution time is 9s
// Serial executionfunc SerializeRun() { start := () xx := []int{1, 2, 3} yy := []int{100, 200, 300} for _, x := range xx { for _, y := range yy { abc(x, y) } } ("Total serial execution time:%s\n", (start)) } func abc(x, y int) { ( * 1) ("x:%d, y:%d\n", x, y) }
Execution results
x:1, y:100
x:1, y:200
x:1, y:300
x:2, y:100
x:2, y:200
x:2, y:300
x:3, y:100
x:3, y:200
x:3, y:300
Total serial execution time: 9.0026338s
Single coroutine group concurrency
- Coroutine Groups are used to reduce O(n^2) to O(n)
- The result execution time is 3s
// Single parallel executionfunc SingleConcurrenceRun() { start := () xx := []int{1, 2, 3} yy := []int{100, 200, 300} for _, x := range xx { wgg := {} for _, y := range yy { (1) go func(x, y int) { defer () abc(x, y) }(x, y) } () } ("Total time for single parallel execution:%s\n", (start)) } func abc(x, y int) { ( * 1) ("x:%d, y:%d\n", x, y) }
result
x:1, y:300
x:1, y:200
x:1, y:100
x:2, y:100
x:2, y:200
x:2, y:300
x:3, y:300
x:3, y:100
x:3, y:200
Total time for single parallel execution: 3.0013813s
Nested concurrent execution
- Perform concurrency using nested coroutine groups.
- Reduce O(n^2) to O(1)
- The result execution time is 1s
// Nested executionfunc NestConcurrenceRun() { xx := []int{1, 2, 3} yy := []int{100, 200, 300} start := () wgg := {} for _, x := range xx { (1) go func(x int) { wg := {} for _, y := range yy { (1) go func(x, y int) { defer () abc(x, y) }(x, y) } () () }(x) } () ("Total time for nested concurrent execution:%s\n", (start)) } func abc(x, y int) { ( * 1) ("x:%d, y:%d\n", x, y) }
result
x:1, y:200
x:3, y:300
x:3, y:200
x:1, y:300
x:2, y:200
x:1, y:100
x:2, y:300
x:2, y:100
x:3, y:100
Total time for nested concurrent execution: 1.0023542s
The above is a detailed explanation of Go concurrency. For more information about Go concurrency, please follow my other related articles!